Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading