Search code examples
reactjsfetchreact-propsuse-effect

how to fetch data from webservice in REACT useEffect function and send it to props object?


I'm trying to fetch data from a webservice to a child component. It looks like Data are fetched ok in console.log() inside useEffect function. I'm not able to work with them in higher function scope. I'd like to access fetched data in the child component (PComponent) through the props object.

Thank you for any advice.

function App(props) {
  let data = undefined;

  useEffect( () => {
    console.log('UseEffect');
    const  fetchData = async () => {
      const result = await axios.get(someUrl)
      data = result.data;             
      console.log('result',data);
      return data;
      
    };
    data = fetchData();
  }, []);
  
  return (
    <PComponent settings = {data}/>
  );
}

export default App;

Solution

  • Try useState hook to store your data. Any state update will rerender the component and therefore data is passed to the child.

    const App = (props) => {
       const [data, setData] = React.useState()
            
       const fetchData = async() => {
          const result = await axios.get(someUrl)
          setData(result);           
       };
            
       // Fetch data when component mounted
       useEffect( () => {
          fetchData()
       }, []);
              
       return (
          <PComponent settings={data}/>
       );
    }
    
    export default App;