Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

348
Visualizações
React newbie here: How do I export data from one component to another?

I have a component Header.js which has an input and button, when I hit button it will fetch data from a third party API. I want to then export the response to another component.

Header.js component as so:

import React, { useState } from 'react';
import Axios from 'axios';


const Header = () => {

    const [ticker, setTicker] = useState('');

    let url = `https://cloud.iexapis.com/stable/stock/${ticker}/quote?token=${process.env.REACT_APP_API_KEY}`;

    const getData = () => {

        Axios.get(url)
        .then((response) => {
            console.log(response.data);
            return response.data;
        })
        .catch(function(error) {
            console.log(error);
        })
    }

    const handleKeypress = (e) => {
        if(e.keyCode === 13) {
        getData();
        }
    }

    return (
        <div className='header'>
            <h1 id='brand'>Stock Tracker: {ticker}</h1>
                <div className='input-flow'>
                    <input onChange={e => setTicker(e.target.value)}
                    onKeyDown={handleKeypress}
                    className='ticker-input' 
                    type='text' 
                    placeholder='Ticker Symbol' 
                    maxLength='5' minLength='1'/>
                    <button className='add' 
                    onClick={getData}
                    type='submit'>Add</button>
                </div>
        </div>
    )
}

export default Header
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

update the state when you receive data from your api in your getData function and pass the state to your another component with props

about 4 years ago · Juan Pablo Isaza Relatório

0

I will assume that the component will be imported and rendered inside Header.js.

You can utilize useState to hold a null value that will be updated to the fetched data. Once the data is available, you will update the state of your empty value, and that value can be passed down to the rendered component.

You will then have access to that data through the new component's props.

    import React, { useState } from 'react';
    import Axios from 'axios';
    import MyComponent from './MyComponent';


const Header = () => {

    const [ticker, setTicker] = useState('');
    const [myData, setMyData] = useState(null);

    let url = `https://cloud.iexapis.com/stable/stock/${ticker}/quote?token=${process.env.REACT_APP_API_KEY}`;

    const getData = () => {

        Axios.get(url)
        .then((response) => {
            console.log(response.data);
            setMyData(response.data)
        })
        .catch(function(error) {
            console.log(error);
        })
    }

    const handleKeypress = (e) => {
        if(e.keyCode === 13) {
        getData();
        }
    }

    return (
        <div className='header'>
            <h1 id='brand'>Stock Tracker: {ticker}</h1>
                <div className='input-flow'>
                    <input onChange={e => setTicker(e.target.value)}
                    onKeyDown={handleKeypress}
                    className='ticker-input' 
                    type='text' 
                    placeholder='Ticker Symbol' 
                    maxLength='5' minLength='1'/>
                    <button className='add' 
                    onClick={getData}
                    type='submit'>Add</button>
                </div>
            {myData && <MyComponent myData={myData} />}
        </div>
    )
}

export default Header

If the component exists outside of Header.js, you may need to either update the state of a common parent component, utilize Redux, or Context.

about 4 years ago · Juan Pablo Isaza Relatório

0

From your description it sounds like you need to maintain state in a parent component, and also a handler that makes the API call. You pass down the handler to Header which is called when the button is clicked. The handler makes the API call, and updates the state. That state is then rendered in the other (Main) component.

const { useState } = React;

function App() {

  const [ data, setData ] = useState([]);

  function handleClick() {
    // Simulated fetch statement - returns data
    const data = [{ id: 1, name: 'Bob' }, { id: 2, name: 'John' }];
    setData(data);
  }

  return (
    <div>
      <Header handleClick={handleClick} />
      <Main data={data} />
    </div>
  );
};

function Header({ handleClick }) {
  return (
    <button
      type="button"
      onClick={handleClick}
    >Get data
    </button>
  );
}

function Main({ data }) {
  return data.map(obj => {
    return <div key={obj.id}>{obj.name}</div>
  });
}

ReactDOM.render(
  <App />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda