简体   繁体   中英

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 开发工具

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

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

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

  }, []);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM