Search code examples
reactjsreact-nativeasynchronousreact-hooksrace-condition

How to run useEffect conditionally that depends on the state from the same cycle


I have a sequence of events that has to happen with one of the events relying on the execution of the previous event.

const [token, setToken] = useState('')
const getToken = async () => {
    try {
        const newToken = await AsyncStorage.getItem(LOGIN_TOKEN)
        setToken(newToken)
    } catch (err) {
        throw new Error(err)
    }
}

useEffect(() => {
    getToken()
    if(token) {
        console.log("the final event")
    }
}, [postAction])

I have the useEffect hook that runs every time postAction changes. I want the "final event" to happen only if getToken runs and retrieves the token. I believe the asynchronous nature of the setToken setter is not happening in time for the token to be set in order to meet the condition of the if statement. Therefore, the final event never gets executed on the first run.


Solution

  • You can add another useEffect hook that specifically looks for changes to the token.

    useEffect(() => {
      getToken();
    }, [postAction]);
    
    useEffect(() => {
      if(token) {
        console.log("the final event")
      }
    }, [token]);