jshuaf / Aquaforces

The land of the free
0 stars 0 forks source link

Redux middleware #86

Closed ssneilss closed 8 years ago

ssneilss commented 8 years ago

Because you are implementing redux framework, the usage of "middlewares" will be super helpful for you to deal with actions

I think it might be better to write socket.onmessage part like:

somewhere in the codes...

socket.onmessage = function(m) {
  // ... some functions
  store.dispatch({ message_type: 'game' , ...m.data })
}

message_middleware.js

export default function middleware({ dispatch, getState }) {
  return next => action => {
    const { message_type, event, ...options } = action
    if (!message_type) next()
    action = require(`.../actions/${message_type}`)[event] // the path to actions/game.js
    dispatch(action(options))
    next()
  }
}

also don't forget to include the middleware into store configuration (see #85 )

jshuaf commented 8 years ago

I see your point, but I don't see why the middleware is required. I would still have to have a switch statement in socket.onmessage because there will be cases with non-pure side effects of receiving an action outside of simply modifying the store.

Couldn't I just put the middleware directly in the socket code?

socket.onmessage = function(m) {
  // parse data
  // call other functions

  const { event, ...options } = m
  action = require(`.../actions/game.js`)[event]
  store.dispatch(action(options))
}
jshuaf commented 8 years ago

I think that the way I specified above would work while the project is still small, but eventually we will need middleware. Wouldn't it be easier to use thunks instead of custom middleware?

ssneilss commented 8 years ago

I think redux-thunk is very good as well :)

jshuaf commented 8 years ago

I'm working on this.