简体   繁体   中英

ReactJS - “setState” with react Hooks, does not merge the state but rather replaces it

I have the following piece of logic, regarding a state with useState and a Websocket endpoint streaming data.

  const [state, setState] = React.useState({ items: [], activity: [] });

  React.useEffect(() => {
    const currentItems = R.isNil(data.items) ? [] : data.items;
    const currentActivity = R.isNil(data.activity) ? [] : data.activity;

    setState({
      ...state,
      items: Array.from(new Set([...state.items, ...currentItems])),
      activity: Array.from(new Set([...state.activity, ...currentActivity]))
    });
  }, [data]);

  console.log('State:', state); // This just replaces the state instead of merging.

But I cannot make the state to merge. It just replaces the state each time with a new value from the stream. What am I missing. I haven't used hooks that much, but it seems weird. I am spreading the state, then updating, each value . Can you tell me what am I doing wrong?

You can do this using a callback function in useState hook:

setState(prev =>{
  ...prev,
  items: Array.from(new Set([...prev.items, ...currentItems])),
  activity: Array.from(new Set([...prev.activity, ...currentActivity]))
});

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