Complex state management made easy.
Your work environment should be as easy as possible, so simple tasks don't require excessive work or a monstrous learning curve. To help maintain your workflow efficiency, this package tackles one of the most difficult challenges of all: state management. We did all the complicated work so you don't have to. While still following best practices and some common patterns, this tool allows you to easily and quickly set up your state, with minimal learning involved.
npm i @thundersolutions/state
First, make sure you've imported the necessary item ...
// import the function from the package
import { createStore } from '@thundersolutions/state'
... Or include it as a UMD.
<script src="https://unpkg.com/@thundersolutions/state/umd/thunderState.min.js"></script>
<script>
const { createStore } = ThunderState
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring
</script>
Then create your state by adding some basic configuration options.
const state = createStore({
state: {
user: {
username: 'demo_user',
email: '[email protected]',
preferences: {
notifications: true,
newsletter: false,
},
},
loggedIn: true,
alert: {
visible: true,
text: 'This is a demo alert'
},
},
actions: {
changeUsername({state, payload}) {
state.user.username = payload
},
toggleLogin({state, payload}) {
state.loggedIn = payload
},
toggleAlert({state, payload}) {
state.alert.visible = payload
},
},
})
Retrieve the state from getters, which are automatically created from your initial state.
console.log(state.getters.loggedIn) // true
console.log(state.getters.user.username) // 'demo_user'
Change the state by dispatching the actions defined above.
state.dispatchers.changeUsername('new_user')
state.dispatchers.toggleAlert(false)
That's all you need for your first simple state! Additionally, there are more options to make your state even more powerful, such as:
- computed values
- watchers
- asynchronous actions
- time travel debugging
Read more about these features in the documentation.
MIT © 2023 Thunder Solutions LLC