• Redux - вызов dispatch из независимого модуля?

    @Aves
    Я бы делал через middleware, примерно так:

    middleware.js
    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);
        }
      };
    };

    actions.js
    export const handleSubmit = data => ({
      type: 'SUBMIT_TO_SERVER',
      payload: data,
      meta: {socket: true}
    });
    
    export const handleChange = event => ({
      type: 'CHANGE_VALUE',
      payload: event.target.value
    });

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

    form.jsx
    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);

    server.js
    socket.on('SUBMIT_TO_SERVER', data => {
      socket.emit('dispatch', {
        type: 'CHANGE_VALUE',
        payload: data ? data.toUpperCase() : ''
      });
    });
    Ответ написан
    Комментировать