Persistent Vuex Store For Only Specific Modules
Here we go again 😅, another yet exciting and educating article. Good day people, I’m so glad you’re reading this article. Today, we’re going to talk about how to create a persistent state for our vuex store.
I’m sure most of you already know how to make a vuex state persistent, but here’s the fun part, we can choose which module to make persistent. This way, we use less storage on our user’s PC.
Okay, let’s dive in.
First off, I’m sure we’ve already set up our vuejs project and vuex state, so I’m just going to skip that.
so let’s start, we first need to install the package that helps us make state persistent. so let’s run;
npm i vuex-persistedstate
done? After that, we move to set it up. Let’s go into our store directory and then into the index.js file.
After that, we need to import this package. Go ahead and import it.
After importing it, we now import our modules.
That’s great. We’ve now imported all the modules we created.
Note: You should understand vuejs, vuex store and state management before reading this article.
In our current use case, we have 5 modules in our state but not all of them are required to be persistent. The necessary modules that should be persistent include: cart, and account.
Now, we are saving the cart module because we need the cart to always be in the state, basically to be saved on your user’s device, and the account because of the user information.
Now to make these modules persistent, we write the following code in our index.js.
and that’s pretty much each. As you can see, we set paths that our createPersistedState() function should save in state.
Think we didn’t save all the necessary modules, go ahead and write the modules you need to be saved.
Each module should be separated with a comma(,).
And that’s it, It’s a wrap.
Thanks again for reading another of my article. Also, if you think this article deserves your claps, go ahead and clap, I’d appreciate every clap.
Much love from bolathedev ❤️!