Search code examples
reactjsreduxwebsocketnext.js

How to get websocket data as state in redux?


My task is to set a websocket and get its data with onMessage() and assign it to redux state. But I don`t know how to implement it. What is the solution?


Solution

  • You have to dispatch you actions inside your event listener:

    // Listen for messages
    socket.addEventListener('message', (socketData) => {
      //event is data passed from socket to you
    
      //dispatch your data accordingly
      store.dispatch({
        type: 'Read the docs',
        payload: socketData
      })
    });