Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using socketio in redux actions

I'm trying to build an application using React, Redux and socket.io ! My question is : how do you initialize event listeners (which are actions in Redux) like this one :

export const addNotif = () => (dispatch) => {
  socket.on('notification', (message) => {
    dispatch(notification(message))
  })
}

in React without having access to the componentWillMount since I'm using functional programing on components.

My current problem is that if I pass the method

addNotif

to my component, every time a new notification comes in, the store is updated, and so the component is re-rendered and therefore it adds another socket.on event and this keeps on going.

Any ideas on how to fix that in a clean way ? Thanks !

like image 826
sulo Avatar asked May 19 '26 07:05

sulo


2 Answers

Try to define and export the function like this:

export const addNotif = (dispatch) => {
  socket.on('notification', (message) => {
    dispatch(notification(message))
  })
}
like image 142
Marco Avatar answered May 22 '26 01:05

Marco


As you mention, you don't want to attach an event listener inside a stateless function. You wanna invert this: notification comes in > dispatch event. This can live outside the lifecycle of react since you can dispatch arbitrary redux actions from anywhere.

If the action is not consumed because there are no clients that's fine. You can fine tune this by absorbing/demuxing events in a redux middleware and/or have components dispatch subscriptions.

index.js

// start() should be called ONCE wherever you have access to the store 
const notifications = require('./notifications');
notifications.start(store.dispatch);

notifications.js

export default {
  start(dispatch) {
    socker.on('connect', () => {
      console.log('Subscribed to notifications');
    });
    socket.on('notification', (payload) => {
      dispatch(({ type: "NOTIF", payload }));
    });
    socket.on('error', (message) => {
      console.log('TODO: handle error');
    })
  },
};

It might be a good idea to abstract away the socketio interface, hence the two files although it's not necessary.

like image 22
Maroshii Avatar answered May 22 '26 01:05

Maroshii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!