Skip to content

Recipes

Jason Miller edited this page Dec 13, 2017 · 1 revision

Redux-like Reducers

We can build a wrapper around createStore() that adds support for redux-style reducers:

import createStore from 'unistore'

function createReducerStore(state, reducer) {
  let store = createStore(state)
  // our reducer is actually an action (they're the same thing!):
  let reduce = store.action(reducer)
  // replacing store.action lets us change how connect() works:
  store.action = fn => (...args) => reduce(fn(...args))
  return store
}

Here's how you'd use that:

// now we can pass a reducer when we create the store:
const store = createReducerStore({ count: 0 }, (state, action) => {
  // the reducer returns a partial state to apply to the store.
  // fun twist: since this is unistore, you could return a Promise.
  if (action.type==='INCREMENT') {
    return { count: state.count + action.value }
  }
})

const actions = {
  increment: () => ({ type: 'INCREMENT', value: 1 })
}

const App = connect('count', actions)(
  ({ count, increment }) => (
    <button onClick={increment}>Count: {count}</button>
  )
)

render(<Provider store={store}><App /></Provider>, document.body)
Clone this wiki locally