I am updating a state from first API call and I want this state value to set another state from next API call.
But even though isSelected State is being set as true from first API, in fetchAllQuotes it is coming as false.
const [isOptionEnabled, setIsOptionEnabled] = useState<boolean>(false);
const [isSelected, setIsSelected] = useState<boolean>(false);
useEffect(() => {
fetchAllAPICalls();
}, []);
const fetchAllAPICalls = async () => {
await fetchAllSelections();
await fetchAllQuotes();
};
const fetchAllSelections = async () => {
const url = getUrlForSelections();
const params = getParamsForSelections();
let selected = false;
await AXIOS_GET(url,params).then((res) => {
res.data.forEach((item)=>{
if(item.isSelected) selected = true;
}
setIsSelected(selected);
}
}
const fetchAllQuotes = async () => {
const url = getUrlForQuotes();
const params = getParamsForQuotes();
let isPresent = false;
await AXIOS_GET(url,params).then((res) => {
res.data.forEach((item)=>{
//doSomething and set isPresent = true;
}
setIsEnabled(isPresent && isSelected);
}
}
>Solution :
When you set state that new value won’t be accessible from state until next render.
One option is you can add the value you want to watch as useEffect dependency, and when it changes, make the second API call then. But this has potential that anytime that value changes the useEffect will be triggered.
So the easiest option could be just return the value you want to set from first API call, then manually pass to the second API call.