starux
v1.0.20
Published
[![Build Status](https://img.shields.io/github/actions/workflow/status/tokhichevsky/starux/npm-publish.yml)](https://github.com/tokhichevsky/starux/actions?query=workflow%3A%22Node.js+Package%22++) [![Build Size](https://img.shields.io/bundlephobia/minzip
Downloads
28
Maintainers
Readme
STARUX
A small library for creating stores.
npm install starux
npm add starux
Create a vanilla store
import createStore from 'starux'
const userStore = createStore({
initialState: {
name: 'Jack',
surname: 'Jackov'
},
reducers: {
setName(state, name) {
state.name = name
},
async setSurname(state, surname) {
const isValid = await validateSurname(surname);
if (isValid) {
state.surname = surname;
}
},
clear() {
return {
name: 'Jack',
surname: 'Jackov'
}
}
},
selectors: {
getName(state) {
return state.name
}
}
})
Reducers turn into actions. You can pass multiple arguments to them. Selectors are used as an aid to avoid placing them in separate functions/objects etc.
Usage
userStore.actions.setName('Anna') // changes state.name to Anna
userStore.actions.setSurname('Baykova') // return Promise
await userStore.actions.setSurname('Baykova') // changes state.surname to Baykova
userStore.get() // returns state
userStore.get((state) => state.name) // returns state.name
userStore.get.getName() // returns state.name
const unsubscribe = userStore.subscribe((state) => doSomething(state)) // calls callback every state changing
Create a react store
import createHookStore from 'starux/react'
const userStore = createHookStore({
initialState: {
name: 'Jack',
surname: 'Jackov'
},
reducers: {
setName(state, name) {
state.name = name
},
async setSurname(state, surname) {
const isValid = await validateSurname(surname);
if (isValid) {
state.surname = surname;
}
},
clear() {
return {
name: 'Jack',
surname: 'Jackov'
}
}
},
selectors: {
getName(state) {
return state.name
}
}
})
Usage
const actions = userStore.useActions();
// ...
actions.setName(); // changes state.name to Anna
actions.setSurname('Baykova') // return Promise
const name = userStore.useSelector('getName') // returns state.name
const name = userStore.useSelector((state) => state.name) // returns state.name
const state = userStore.useSelector() // returns state
userStore.useSubscribe((state) => doSomething(state)) // calls callback every state changing