K
K
KELeborn2016-09-08 18:40:27
JavaScript
KELeborn, 2016-09-08 18:40:27

Redux - call dispatch from independent module?

help me figure out how to do it better.
I am learning Redux, I am writing an application that listens to WebSockets,
upon receipt of some messages, changes in the application should be called using dispatch, BUT:
how convenient is it to call dispatch from a separate module? more precisely, how to get access?
so far, dispatch is passed to methods each time, which can be passed more further, on action'y for example - a little crutch

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aves, 2016-09-09
@KELeborn

I would do it through middleware, something like this:

import io from 'socket.io-client';

export default ({dispatch, getState}) => {
  const socket = io();
  socket.on('dispatch', action => { dispatch(action) });

  return next => action => {
    const {type, payload, meta} = action;
    if (meta && meta.socket) {
      socket.emit(type, payload);
    } else {
      next(action);
    }
  };
};

export const handleSubmit = data => ({
  type: 'SUBMIT_TO_SERVER',
  payload: data,
  meta: {socket: true}
});

export const handleChange = event => ({
  type: 'CHANGE_VALUE',
  payload: event.target.value
});

export default (state = '', {type, payload}) => {
  if (type == 'CHANGE_VALUE') return payload;
  else return state;
};

import {connect} from 'react-redux';
import {handleChange, handleSubmit} from 'actions';

const Form = ({state, handleChange, handleSubmit}) => <form onChange={handleChange} onSubmit={handleSubmit}>
  <input type='text' value={state} />
  <button>Submit</button>
</form>;

export default connect(state => state, {handleChange, handleSubmit})(Form);

socket.on('SUBMIT_TO_SERVER', data => {
  socket.emit('dispatch', {
    type: 'CHANGE_VALUE',
    payload: data ? data.toUpperCase() : ''
  });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question