I am trying to create my first Redux middleware to handle a persistent Socket.IO connection to a chat server. The Redux app should only create the Socket.IO connection after the user has logged in. store.user.id
in the Redux store is not null
if the user is logged in.
Question: How can be create the Socket.IO connect only when the user has logged in, and disconnect from it when the user has logged out?
In the example code below, the Socket.IO conenction is made immediately.
import io from 'socket.io-client';
const chatMiddleware = () => {
return store => {
// HOW TO Connect to socketio server only after being logged in?
const socket = io('http://localhost:3002');
socket.on('connect', () => {
console.log('Connected to chat server.');
socket.emit('msg', 'hello world!');
});
return next => action => {
if (action.type == SEND_MESSAGE) {
console.log('middleware intercepted SEND_MESSAGE')
socket.emit('msg', action.payload);
return;
}
return next(action);
}
}
}
export default chatMiddleware
System Environment
- react-dom@16.13.1
- react-redux@7.2.0
- react@16.13.1
- redux@4.0.5
- Node v14.0.0