Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way of dispatching an action not tied to a component with Redux?

Tags:

reactjs

redux

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!!

like image 845
Slartibartfast Avatar asked Mar 23 '16 17:03

Slartibartfast


2 Answers

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

like image 66
Brandon Avatar answered Nov 01 '22 06:11

Brandon


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).

like image 23
markerikson Avatar answered Nov 01 '22 06:11

markerikson