roblafeve / redux-factory

Composable, curried factory for creating Redux reducers and actions
MIT License
9 stars 2 forks source link

Add default redux example and comparative redux-factory version #5

Open roblafeve opened 7 years ago

roblafeve commented 7 years ago

I wish your documentation took the default redux example and showed how your library simplified it. Then show a more complex example.... and simplify that.

roblafeve commented 7 years ago
import { createStore } from 'redux'
import factory from 'redux-factory'

/**
 * This is a reducer, a pure function with (state, action) => state signature.
 * It describes how an action transforms the state into the next state.
 *
 * The shape of the state is up to you: it can be a primitive, an array, an object,
 * or even an Immutable.js data structure. The only important part is that you should
 * not mutate the state object, but return a new object if the state changes.
 *
 * In this example, we use a `switch` statement and strings, but you can use a helper that
 * follows a different convention (such as function maps) if it makes sense for your
 * project.
 */
// function counter(state = 0, action) {
//   switch (action.type) {
//   case 'INCREMENT':
//     return state + 1
//   case 'DECREMENT':
//     return state - 1
//   default:
//     return state
//   }
// }

const prefix = 'counter'
const initialState = 0;
const transforms = {
  INCREMENT: state => state + 1,
  DECREMENT: state => state - 1,
  INCREMENT_BY: (state, payload) => state + payload,
  DECREMENT_BY: (state, payload) => state - payload
}

const counter = factory(initialState, transforms, prefix)

// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
// let store = createStore(counter)
let store = createStore(counter.reducer)

// You can use subscribe() to update the UI in response to state changes.
// Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly.
// However it can also be handy to persist the current state in the localStorage.

store.subscribe(() =>
  console.log(store.getState())
)

// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
// store.dispatch({ type: 'INCREMENT' })
store.dispatch(counter.INCREMENT())
// 1
// store.dispatch({ type: 'INCREMENT' })
store.dispatch(counter.INCREMENT())
// 2
// store.dispatch({ type: 'DECREMENT' })
store.dispatch(counter.DECREMENT())
// 1

store.dispatch(counter.DECREMENT_BY(10))
// -9

store.dispatch(counter.INCREMENT_BY(100))
// 91