0

I'm fetching the data from an API and setting a state as a response. Below is the code

const createLeagueReq = (startTimeInMillis, createLeaguePath) => {
    axios
      .post(createLeaguePath, {
        name: leagueName,
        displayName: leagueDisplayName,
        startTime: startTimeInMillis,
      })
      .then((response) => {
        if(response!==null){
      setLeagueCreateResponse(response.data);
        }
      });
   
  };

  const fetchData = () => {
    const startTimeInMillis = new Date(startTime).getTime();
    console.log("start time to Millis", startTimeInMillis); //1673654400000
    const createLeaguePath = `${defaultUrl}${createLeagueUrl}`;
    console.log("createLeagueUrl", createLeagueUrl);
    createLeagueReq(startTimeInMillis, createLeaguePath);
       if (leagueResponse !== null) {
      const leagueId = leagueResponse.result.id;
      console.log("league id", leagueId);
      setOkResponse("hello");
    } else {
      setOkResponse("bye");
    }
  };

For the 1st request, the API return a response, but the state variable shows undefined. I know that react states don't get updated immediately. I tried to set a callback for setLeagueCreateResponse, that didn't work. Even I tried to use useRef hook. That didn't work too. If I use useEffect the page is rendering continuously, but not showing the response when I call the fetchData function on a button click. How should I make it work to get a response as "hello" on the first click of a button?

PRJ
  • 73
  • 9
  • did you keep leagueResponse state in your useEffect dependency list? – Dipo Ahmed Jan 14 '23 at 12:53
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Terry Jan 14 '23 at 12:53
  • `createLeagueReq` contains an async POST request operation, and in addition it also sets the state in your component, which is by itself another async operation. Assuming that `setLeagueCreateResponse` sets the state `leagueResponse`, your strategy is to simply listen to changes to `leagueResponse` by adding to the dependency list of a `useEffect` hook. – Terry Jan 14 '23 at 12:55
  • useEffect(() =>{ fetchData(); }, [leagueResponse]); tried this, now getting cannot read properties of undefined error – PRJ Jan 14 '23 at 13:01
  • 1
    You got the order wrong. You should call useEffect for logic that needs the async response. – Terry Jan 14 '23 at 13:25
  • I didn't understand it clearly. Sorry, I'm beginner. – PRJ Jan 14 '23 at 13:36

0 Answers0