import { createStore } from 'smitty'// Create a store with initial stateconst initialState = { count: 0 }const store = createStore(initialState)store.createActions({ add: 'count/ADD'})// add a reducerstore.handleActions({ [store.actions.add]: (state, e, type) => { // increment foos by amount return Object.assign({}, state, { count: state.count + e.amount }) }, '*': (state, e, type) => { // '*' can be used for all kinds of fun stuff console.log(e, type) if (type === 'count/ADD') { //...do something } return state }})store.actions.add({ amount: 5 })console.log(store.state) // logs `{ count: 5 }`
const store = createStore({ name: 'Arrow' })store.handleActions({ 'update/NAME': function (state, payload) { // I really don't care if you return a new state // Nobody is judging. Do what your ❤️ tells you. // Just be consistent return Object.assign({}, state, payload) }})console.log(store.state) // logs { name: 'Arrow' }store.emit('update/NAME', { name: 'River' })console.log(store.state) // logs { name: 'River' }
createActions(): (function)
arguments
actionMap: (object)
Object where key is the action creator's name and the value can be of type string or function.
If the value is a string, an action creator is attached to store.actions as a function that accepts one argument, payload.
store.createActions({ add: 'count/ADD'})// The following are functionally equivalentstore.actions.add(1)store.emit('count/ADD', 1)
Action creators with a string value can be used as the key in your actionMap in handleActions.
import { createStore } from 'smitty'// Create a store with initial stateconst initialState = {}const store = createStore(initialState)// add our reducerstore.handleActions({ 'api/GET_ROOM': (state, { id, res }) => { return { ...state, [id]: { ...state[id], ...res.data } } }})// create our action creatorsconst actions = { requestRoom (id) { return async (emit, state) => { emit('REQUEST_ROOM', { id, res: { data: { id } } }) const res = await window.fetch(`https://api.mysite.com/${id}`) res.data = await res.json() emit('REQUEST_ROOM', { id, res }) } }}// When calling emit with a function argument, the function will be called with `emit` and `state` as argumentsconst result = store.emit(actions.requestRoom('1a'))// Return whatever you like from your action creatorconsole.log(result) // logs "Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}"// After the fetch call, `REQUEST_ROOM` is fired a second time with our response dataresult.then(() => console.log(store.state)) // logs `{ 1a: { id: '1a', title: 'My Room' }``
Class As Reducer
Reducers are iterated with for (let type in reducer) {...} with no obj.hasOwnProperty check so this works.