0

I have the following bit of code

    const [inProgress, setInProgress] = useState(value);

    useEffect(() => {
      missionState.mission_summary.length > 0 ? setInProgress(true) : setInProgress(false);
      console.log(missionState.mission_summary.length > 0) // false
      console.log(inProgress) // true
    });

In the last two lines, I logged the output. I would assume inProgress would be false since the condition that sets it is false. I am new-ish to React, so I am curious what is happening here.

  • setState is asynchronous, so you don't see the change immediately after the call ... – Ergis Dec 01 '22 at 17:05
  • Yes! Thank you for the responses. In the larger context of the application, I may have to abandon the above approach. Due to the async nature, I was getting a lot of errors for properties not found on a particular object because I was relying on the code I posted above to conditionally read those properties. I'm sure there is an elegant way to do this is React, but I'm still learning the ropes. –  Dec 01 '22 at 18:14

2 Answers2

1

setstate is asynchronus. use useEffect to catch changes to the state

useEffect(() => {
      missionState.mission_summary.length > 0 ? setInProgress(true) : setInProgress(false);
      console.log(missionState.mission_summary.length > 0) // false
     
}, []);


useEffect(() => {
   console.log(inProgress) 
}, [inProgress])
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
0

The problem is that you are trying to get and updated value from setState right after when setState is asynchronus. You should try to listen for inProgress change on another useEffect or to create a useCallback function that listens for the "inProgress" change and responds with the updated value.