0.2.1 • Published 8 years ago
little-atom v0.2.1
little-atom
State management without the bulk.
...Inspired very heavily by tiny-atom, but not as minimal... get it?
Usage
$ yarn add little-atomExample
const createAtom = require('little-atom')
const initialState = { score: 0 }
const actions = {
increaseScore ({ get, mutate, actions }, points) {
const { score } = get()
mutate({ score: score + points })
actions.checkScore()
},
decreaseScore ({ get, mutate, actions }, points) {
const { score } = get()
mutate({ score: score - points })
},
checkScore ({ get, mutate, actions }, payload) {
const { score } = get()
if (score >= 1000) {
console.log('You win! ...something')
actions.restart()
}
},
restart ({ get, mutate, actions }, payload) {
console.log('Restarting')
mutate(initialState)
}
}
const onMutation = ({ score }) => {
console.log(`Your score is ${score}`)
}
const atom = createAtom(initialState, actions, onMutation)
atom.actions.increaseScore(500)
// -> Your score is 500
atom.actions.decreaseScore(100)
// -> Your score is 400
atom.actions.increaseScore(600)
// -> Your score is 1000
// -> You win! ...something
// -> Restarting
// -> Your score is 0Async Example
nst Preact = require('preact')
const axios = require('axios')
const createAtom = require('little-atom')
const initialState = {
loading: false,
topScore: {}
}
const actions = {
async loadData ({ mutate }, payload) {
mutate({ loading: true })
const { data } = await axios.get('/top-score')
mutate({
loading: false,
topScore: data.topScore
})
}
}
const atom = createAtom(initialState, actions, render)
const App = ({ loadData, state }) => {
const { loading, topScore } = state
if (loading) {
return <div>Loading...</div>
} else {
if (typeof topScore === 'undefined') {
return <button onclick={loadData}>Get top score</button>
} else {
return <div>{`The top score is ${topScore}`}</div>
}
}
}
function render (state) {
Preact.render(<App loadData={atom.actions.loadData} state={state} />, document.body)
}
render(initialState)API
createAtom(initialState, actions, onMutation, options)
Create an atom.
initialState- should be an object, defaults to{}actions- an object ofaction(atom, payload)functions, keyed by the action nameatom- an instance of atompayload- the payload the action was called with
onMutation(state, chain)- a function called after each mutationstate- current statechain- the chain of actions called to arrive at this mutation (for debugging)
options- These are mainly used for debugging purposesoptions.onAction- called when an action is runoptions.mutator(state, update)- custom function to mutate state. Defaults toObject.assign({}, state, update)options.get(state)- custom function to return a copy of the current state. Defaults toObject.assign({}, state)
Returns
An instance of atom
atom.get()- gets the current stateatom.mutate(update)- mutates the state withupdateatom.actions- object of actions available with identical signature as the passed inactionsobject