I have a project in which a nodejs server delivers push events to a react dashboard through socket.io, I'm using Redux. When new data is received an action is triggered to update all the relevant components, although I'm not sure that the way I'm doing it is the right one.
This is how I monitor for new incoming data from the server:
socket.on('incidents', state => {
boundActionSetIncidentsList(state);
});
And this is the bounded action creator that is invoked on new data:
import { store } from '../index';
export function boundActionSetIncidentsList(incidents) {
store.dispatch(actionSetIncidentsList(incidents));
}
I need the store in order to dispatch the action, as you can see I'm brutally importing it from the main index.js
. This is how it is created:
export const store = createStore();
Being very new to react and redux I was wondering what is the redux-way of dispatching actions that are not triggered from a container or presentational component. Thank you!!
You could wrap your code which sets up the socket listener to be a function which takes the store as an argument. So at least your client main routine can setup the store and pass it in to the socket listener when it is ready.
You could also try using a library to help. Here is some redux middleware which can automatically dispatch actions into the store when the server sends data:
https://github.com/itaylor/redux-socket.io
General suggestion would be to manage your socket connection in either a Redux middleware (which has access to the store's dispatch
method), or in a React component that handles the socket on component mount/unmount and could use the React-Redux connect
function to gain access to dispatch
(or pre-bind action creators for use with socket events).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With