yardforsale
yardforsale

Reputation: 11

React Context - Set state then reference it straight after?

I am working with a list of items and I want to set a selected item id, then fetch the selected item using the id.

I am updating the state of a context using reducers which works, but when referencing the property of the state, it doesn't see the updated value.

Component.js

  useEffect(() => {
    setSelectedId(5);
    getSelectedItem();
  }, []);

Context.js

  const initialState = {
    selectedId: 0,
  };

  const [state, dispatch] = useReducer(ItemReducer, initialState);

  const setSelectedId = id => dispatch({ type: SET_SELECTED_ID, payload: id });

  // HERE IT THINKS 'state.selectedId' IS 0
  const getSelectedItem = async () => {
     const selectedItem = await fetch(url + state.selectedId);
  };

Chrome dev tools

The Chrome dev tools show the selected id property is updated to 5, but the getSelectedItem function sees 'selectedId' as 0 not 5.

This could be a simple issue and any help would be appreciated.

Thanks

Upvotes: 0

Views: 68

Answers (2)

pasha_codes
pasha_codes

Reputation: 635

You could move getSelectedItem(); into its own useEffect that's dependent on the selectedItemId, that way it will only perform getSelectedItem once the value of selectedId is set.

useEffect(() => { 
   if(selectedId) getSelectedItem();
}, [selectedId]);

Upvotes: 0

Luke
Luke

Reputation: 557

You will need to resolve the promise that would be returned. Something like:

useEffect(() => {
    setSelected(5).then(getSelectedItem());

  }, []);

Upvotes: 1

Related Questions