State management is a very important part of modern frontend development. Libraries such as React and Vue have libraries (Redux, Vuex) dedicated to state management.
But what about vanilla JS?
Recently, I was developing a vanilla app. This app required robust state management because variables weren't enough. I thought of what to use to manage state and stumbled on Beedle. I totally forgot that I could use Redux without React. I guess it doesn't matter anymore. I have already learnt Beedle.
So then, I'm writing about Beedle.
Beedle is basically a tiny library which gives you greater control over your app's state. Three important concepts exist within Beedle.
- Actions
- Mutations
- State
But before I say any other thing, here's a sample app I built.
The Three Musketeers
Actions
Actions within Beedle are methods in an actions' object. These actions commit are stuff which transmits changes to methods called
const actions = {
colorClick(context, payload){
context.commit('handleClick', payload)
}
};
Mutations
Mutations being methods which modify the state. Just like setState in react, but in this case, the app's state is directly modified.
const actions = {
handleClick(state, payload){
state.color = payload.color;
state.coloredText = payload.text;
return state;
}
};
InitialState
InitialState is simply the initial state of the app
const initialState = {
color:'',
coloredText:'black',
preText:'I am',
}
};
The Store
The store is an object which contains the state of the app. Since Beedle is basically an exported class, an instance of the store has to be created like this
const store = new Store({ actions, mutations, initialState });
Similar to redux, the state can be gotten from the store.
The dispatch method exists on the store object
Actions are dispatched to the store when we want the state to change
Something like this
titleSetter.addEventListener('input', () => {
store.dispatch('textInput', titleSetter.value)
})
Here's the flow
events => actions => mutations => change state => subscribed variabled are altered;
The store gives one the ability to update variables if the state changes. Only subscribed variables are altered.
storeInstance.subscribe(state => {
textColor.style.color = state.color;
})
So then, we have a small library which we can use to manage state.
IMHO, I didn't explain anything in this post. If you want to learn to use Beedle, the docs are the best resource. But thanks for reading anyways.
Top comments (2)
Thanks for sharing this tip Chukwujama! Just one thing I had trouble accessing the Beedle link from you article, Here is the link if others want to access it? Beedle
Keep up the great work!
Thanks a lot Aaron.