Home > front end >  React newbie here: How do I export data from one component to another?
React newbie here: How do I export data from one component to another?

Time:12-30

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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>

  • Related