Home > Software design >  React Hooks setState on update to push new object return duplicates / multiple object per each push
React Hooks setState on update to push new object return duplicates / multiple object per each push

Time:04-20

I have a data coming from socket.io an a  React useState which is an empty array. 

1: What I want to do is to push every data that comes from socket.io as an object into the array.

Below is the code...

const [getOrder, setGetOrder] = useState([]);

 useEffect(() => {
socket.on('json', (data) => {
  const { number, table } = data.order;
  if(number && table) {
    setGetOrder((prevState) =>  [...prevState, { number, table }])
  }
});

}, [socket, setGetOrder]);

The issue am facing is that, every I push new object into my array, it return a duplicate or multiples object with the same data but diffrent keys...

Below is the sampl data am getting...

    0: {number: '303', table: 'bulk'}
1: {number: '303', table: 'bulk'}
2: {number: '304', table: 'bulk'}
3: {number: '304', table: 'bulk'}
4: {number: '304', table: 'bulk'}
5: {number: '304', table: 'bulk'}

I can't seems to get where am getting t wrong. but any help will be appreciated

CodePudding user response:

You need to specify a dependency array, in this case an empty one. Currently, the useEffect triggers on every render.

 useEffect(() => {
  socket.on('json', (data) => {
    const { number, table } = data.order;
    if(number && table) {
      setGetOrder((prevState) =>  [...prevState, { number, table }])
  }
}, []);

This useEffect has no dependencies that are part of the data flow, so specifying an empty dependency array tells React to update this effect once - when the component mounts.

CodePudding user response:

I believe you should remove setGetOrder, and have the dependency array set only to [socket]. That way it runs when the socket gets updated. Right now your duplication seems to be from the fact that your useEffect runs once the socket is updated, and then once again when getOrder is updated but before the socket is updated again. This is what is causing the duplication.

  • Related