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?