0.3.0 • Published 3 years ago

boko v0.3.0

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

Boko

A simple yet scalable state-management solution built on-top of redux.

1. Installation

Install boko using:

npm install boko

2. Setup redux

First we must setup the redux store using the boko reducer and middleware:

import {createStore, applyMiddleware} from "redux"
import {reducer, middleware} from "boko"

const store = createStore(reducer, applyMiddleware(middleware))

3. Define state nodes

Now we can define "state nodes". These are essentially individual atoms of state and it is up to you to decide how you wish to divide your app state across these nodes.

import boko from "boko"

const foo = boko(0)
const bar = boko(1)

In the example above, we've created two nodes, each initially storing a distinct number.

4. Create thunks to modify your state

Mutating state is done via thunks (hence the middleware). For example, lets write a thunk that swaps the values of these two state nodes.

const swapValues = (store) => {
    // Grab the initial values of the state nodes.
    const fooVal = foo.get(store)
    const barVal = bar.get(store)
    
    // Swap 'em.
    foo.set(barVal)(store)
    bar.set(fooVal)(store)
}

5. Connect to React

Now we can (optionally) connect our state up to React components. As this is built ontop of Redux, we can use the standard react-redux library to achieve this. We'll create a higher-order component that provides the values of foo and bar as props, as well as a nullary method to swap said values.

import {connect} from "react-redux"

export const higherOrderComponent = connect(
    (state) => ({
        // Use the lens methods to grab the values of the state nodes.
        foo: foo.lens(state),
        bar: bar.lens(state)
    }),
    (dispatch) => ({
        // The middleware we've included allows us to dispatch thunks directly.
        swap: () => dispatch(swapValues)
    })
)