Aftab
Aftab

Reputation: 61

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

Upvotes: 1

Views: 746

Answers (3)

Giorgi Moniava
Giorgi Moniava

Reputation: 28685

When you set state that new value won't be accessible from state until next render (unless you use set state with updater function).

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.

Upvotes: 3

OppaHeinz
OppaHeinz

Reputation: 296

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

// [...]

Upvotes: 1

Milind Barve
Milind Barve

Reputation: 430

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.

Upvotes: 1

Related Questions