1.0.20 • Published 2 years ago
starux v1.0.20
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
1.0.19
2 years ago
1.0.18
2 years ago
1.0.17
2 years ago
1.0.16
2 years ago
1.0.9
2 years ago
1.0.8
2 years ago
1.0.7
2 years ago
1.0.6
2 years ago
1.0.11
2 years ago
1.0.10
2 years ago
1.0.20
2 years ago
1.0.15
2 years ago
1.0.14
2 years ago
1.0.13
2 years ago
1.0.12
2 years ago
1.0.5
2 years ago
1.0.4
2 years ago
1.0.3
2 years ago
1.0.2
2 years ago
1.0.1
2 years ago
0.1.0
2 years ago