Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 282
Nick G Avatar asked Nov 01 '25 12:11

Nick G


1 Answers

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;
like image 114
Ashik S Nair Avatar answered Nov 04 '25 02:11

Ashik S Nair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!