Skip to content Skip to sidebar Skip to footer

Socket.io Resets React State?

I'm running into a weird problem when working with React and Socket.io. Appreciate anyone might be able to help. Goal: -->1. socket.io emits an event to react frontend with a l

Solution 1:

Turns out I was using uuidv4() to generate a unique key for the component rendering this one.

...

return (
  <div key={uuidv4()}>
      {message.buttons && <ButtonsMessage socket={this.props.socket} user={this.props.user} buttons={message.buttons} />}
  </div>
)
...

Did some digging and found that will cause the key to being regenerated everytime the component renders, which will lead to remounting of the child component, which in turn resets its state.

I moved the key generation to socket.io server side and pass that key to the component as the unique key and fixed the problem.

<div key={message.messageId}>
    {message.buttons && <ButtonsMessage socket={this.props.socket} user={this.props.user} buttons={message.buttons} />}
</div>

Thanks to everyone who helped!


Post a Comment for "Socket.io Resets React State?"