Home > database >  How to update state and use the same in another async function
How to update state and use the same in another async function

Time:09-17

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);
      }
    }
    

CodePudding user response:

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.

CodePudding user response:

setter calls for state variable in ReactJS are async. So even if you set state (setIsSelected) it is not reflected immediately and hence if you use isSelected in subsequent method , it's not guaranteed to work.

you can pass 'selected' as parameter to fetchAllQuotes method and use it for determining setIsEnabled.

CodePudding user response:

If I read your intention correctly, return both values in the functions in the effect and set the state value afterwards.

const fetchAllAPICalls = async () => {
    const isSelected = await fetchAllSelections();
    const isPresent = await fetchAllQuotes();
    setIsEnabled(isPresent && isSelected);
};

// [...]
  • Related