React state is not updated after dispatch call using React useContext hook

Viewed 1559

Yow guys, React beginner here.
So basically, I am trying to fetch the updated state using React useContext hook.

The state is set inside a function call where the dispatch is placed, and the function call is bind to the button onClick event.

The function where the dispatch is called:

const fetchLocation = async (id: number) => {
    const [, result] = await getLatestLocation()
    dispatch({ 
      type: "LOCATION_FETCHED", 
      payload: result 
    })
    console.log(result) //this prints the latest/updated location even on button first click
  }

Reducer:

case "LOCATION_FETCHED": {
      return {
        ...state,
        location: payload,
      }
    }

The function call in the component:

const { 
    fetchLocation, 
    location
   } = React.useContext(locationContext)
  const [fetchingLocation, setFetchingLocation] = useState(false)
  const getLocation = (id: number) => {
     fetchLocation(id)
      .then(() => {
        setFetchingLocation(true)
      })
      .finally(() => {
        setFetchingLocation(false)
        console.log(location) //this prints nothing or empty on the first button click
      })
  }

Button onClick function bind:

onClick={() => getLocation(143)}

I'm not sure what is happening, the first click will log nothing but on the second click, I got the updated location state.

1 Answers

As the comments say, the dispatch works asynchronously. So if you want to know the new value you should use the useEffect hook like this.

useEffect(() => {
  console.log(location)
}, [location])

You can read more about here: https://reactjs.org/docs/hooks-effect.html

Related