Search code examples
reactjsreact-state-management

Is it possible to initialize the state of a component with API data before the initial mounting of the component?


In my react application I'd like to initialize the state of my component using API data. One way that would work is to make the API call in useEffect() and then set the state after the API call, but this would occur after the initial mounting of the component.

I'm just wondering if there are other ways to initialize the state before the initial mounting of the component? Here is what I tried and it doesn't work.

async function getAns() {
    let output = [];
    //make api calls and assign data to output
    //.......
    return output;
  };

const [playersList, setPlayersList] = useState(getAns());

Thanks a lot for any advice!


Solution

  • You can use async-await with your funtion and load the components only when the state has the response data from your API call.

    import React,{useState, useEffect} from 'react';
    
    const Component = () => {
      const [playerList, setPlayerList] = useState();
    
     async function getAns(){
    
       let output = await //make api calls and assign data to output
        
       return setPlayerList(output);
    
      };
    
      useEffect(() => {
        getAns();
      }, [])
    
    return (
      {playerList && (
        // Component jsx elements
    )}
    )
    }
    
    export default Component;