Welcome to bistate 👋
Create the next immutable state tree by simply modifying the current tree
bistate is a tiny package that allows you to work with the immutable state in a more mutable and reactive way, inspired by vue 3.0 reactivity API and immer.
Homepage
🏠Benefits
bistate is like immer but more reactive
- Immutability with normal JavaScript objects and arrays. No new APIs to learn!
- Strongly typed, no string based paths selectors etc.
- Structural sharing out of the box
- Deep updates are a breeze
- Boilerplate reduction. Less noise, more concise code.
- Provide react-hooks API
- Small size
- Reactive
Environment Requirement
- ES2015 Proxy
- ES2015 Symbol
How it works
Every immutable state is wrapped by a proxy, has a scapegoat state by the side.
immutable state
+ scapegoat state
= bistate
- the immutable target is freezed by proxy
- scapegoat has the same value as the immutable target
- mutate(() => { the_mutable_world }), when calling
mutate(f)
, it will- switch all operations to scapegoat instead of the immutable target when executing
- switch back to the immutable target after executed
- create the next bistate via
scapegoat
andtarget
, sharing the unchanged parts - we get two immutable states now
Install
npm install --save bistate
yarn add bistate
Usage
Counter
// import react-hooks api from bistate/react { // create state via useBistate let state = // safely mutate state via useMutate let incre = let decre = return <div> <button onClick=incre>+1</button> statecount <button onClick=decre>-1</button> </div> }
TodoApp
{ let edit = /** * bistate text is reactive * we will pass the text down to TodoInput without the need of manually update it in Todo * */ let text = // create a mutable function via useMutate let handleEdit = let handleEdited = let handleKeyUp = let handleRemove = let handleToggle = return <li> <button onClick=handleRemove>remove</button> <button onClick=handleToggle>todocompleted ? 'completed' : 'active'</button> editvalue && <TodoInput text=text onBlur=handleEdited onKeyUp=handleKeyUp /> !editvalue && <span onClick=handleEdit>todocontent</span> </li> } { let handleChange = return <input type="text" ...props onChange=handleChange value=textvalue />}
API
useBistate(array | object, bistate?) -> bistate
receive an array or an object, return bistate.
if the second argument is another bistate which has the same shape with the first argument, return the second argument instead.
let { // if props.counter is existed, use props.counter, otherwise use local bistate. let state = let handleClick = return <div onClick=handleClick>statecount</div>} // use local bistate<Child />// use parent bistate<Child counter=state />
useMutate((...args) => any_value) -> ((...args) => any_value)
receive a function as argument, return the mutable_function
it's free to mutate any bistates in mutable_function, not matter where they came from(they can belong to the parent component)
useBireducer(reducer, initialState) -> [state, dispatch]
receive a reducer and an initial state, return a pair [state, dispatch]
its' free to mutate any bistates in the reducer funciton
const Test = { let state dispatch = let { } let { } // render view}
useComputed(obj, deps) -> obj
Create computed state
let state = // use getter/setterlet computed = let handleEvent =
useBinding(bistate) -> obj
Create binding state
A binding state is an object has only one filed { value }
let state = let text = // don't do this// access field will trigger a react-hooks// you should always use ECMAScript 6 (ES2015) destructuring to get binding statelet bindingState = if xxx xxx = bindingStatexxx let { console // some text console // some text textvalue = 'some new text' console // some new text console // some new text}
It's useful when child component needs binding state, but parent component state is not.
{ let handleChange = return <input type="text" ...props onChange=handleChange value=textvalue />} { let state = let fieldA fieldB fieldC = return <> <Input text=fieldA /> <Input text=fieldB /> <Input text=fieldC /> </>}
view(FC) -> FC
create a two-way data binding function-component
const Counter = // use local bistate<Counter /> // create a two-way data binding connection with parent bistate<Count count=parentBistatecount />
useAttrs(initValue) -> Record<string, bistate>
create a record of bistate, when the value in props[key] is bistate, connect it.
useAttrs must use in view(fc)
const Test = // use local bistate<Counter /> // create a two-way data binding connection with parent bistate<Count count=parentBistatecount />
useAttr(key, initValue) -> bistate
a shortcut of useAttrs({ [key]: initValue })[key]
, it's useful when we want to separate attrs
createStore(initialState) -> { subscribe, getState }
create a store with an initial state
store.subscribe(listener) -> unlisten
subscribe to the store, and return an unlisten function
Every time the state has been mutated, a new state will publish to every listener.
store.getState() -> state
get the current state in the store
let store = let state = store let unlisten = store
mutate(f) -> value_returned_by_f
immediately execute the function and return the value
it's free to mutate the bistate in mutate function
remove(bistate) -> void
remove the bistate from its parent
isBistate(input) -> boolean
check if input is a bistate or not
debug(bistate) -> void
enable debug mode, break point when bistate is mutating
undebug(bistate) -> void
disable debug mode
Caveats
-
only supports array and object, other data types are not allowed
-
bistate is unidirectional, any object or array appear only once, no circular references existed
let state =
- can not spread object or array as props, it will lose the reactivity connection in it, should pass the reference
// don't do this<Todo ...todo /> // do this instead<Todo todo=todo />
-
can not edit state or props via react-devtools, the same problem as above
-
useMutate or mutate do not support async function
const Test = { let state = // don't do this let handleIncre = // do this instead let incre = let handleIncre = async { let n = await } return <div onClick=handleIncre>test</div>}
Author
👤 Jade Gu
- Twitter: @guyingjie129
- Github: @Lucifier129
🤝 Contributing
Contributions, issues and feature requests are welcome!
Feel free to check issues page.
Show your support
Give a ⭐️ if this project helped you!
📝 License
Copyright © 2019 Jade Gu.
This project is MIT licensed.
This README was generated with ❤️ by readme-md-generator