DEV Community

Discussion on: React... Why so complicated...?

Collapse
 
vonheikemen profile image
Heiker

What if you push (almost) all the responsability to the actions?

You could tweak redux a little bit by writing a middleware.

const thunk = store => next => action =>
    typeof action === 'function'
      ? next({type: '', state: action(store.getState)})
      : next(action)

Then create a very generic reducer.

const reducer = function(state, action) {
  if(typeof action.state !== 'undefined') {
    return Object.assign({}, state, action.state)
  }

  return initialState()
}

And now you can have actions like this:

let nextTodoId = 0
export const addTodo = text => state => {
  // complexity, my old friend, you can live here

  return {
    todos: state().todos.concat({
      id: nextTodoId++,
      text,
      completed: false
    })
  }
}

export const setVisibilityFilter = filter => state => ({
  visibilityFilter: filter
})
Collapse
 
joetex profile image
Joel Ruiz • Edited

This has lots of potential! Thank you for sharing.

With a bit more tweaks this could be very clean for developers to use without much thought. I will play with this trick thanks!