DEV Community

WebCraft Notes
WebCraft Notes

Posted on • Originally published at webcraft-notes.com

Implementing Pinia for Efficient State Management in Nuxt.js Online Stores

Implementing Pinia for Efficient State Management in Nuxt.js Online Stores

Check this post in my web notes!

In this article, we will talk about the Pinia store for Nuxt.js projects. We already built the main pages for our e-commerce store and are ready to populate our project with functionality, but first, we need to configure the state management system. Why? Because we want to store our e-commerce data and part of its functionality in a state management system so that it would be available from each component where we will need it. I think Pinia is the best variant for this purpose. Additionally, you can check this Pinia guide, or let's just walk through it together.

  1. Installing and Configuring Pinia in Nuxt.js Project
  2. Creating the First Pinia Store

With the importance of state management established, let's dive into the practical implementation of Pinia in our Nuxt.js e-commerce project. We'll start by:

1. Installing and Configuring Pinia in Nuxt.js Project

We will use the official documentation which recommends using the "npm install pinia" command for Vue.js projects, but we need to move to the Nuxt.js section, and there is a special package for Nuxt.js over here. According to Pinia documentation, we need to use the command: "npm install pinia @pinia/nuxt". Then we need to open the nuxt.config.js file in the project root directory and add the @pinia/nuxt module.

export default defineNuxtConfig({
  devtools: { enabled: false },
  modules: [
    '@pinia/nuxt',
  ],
})
Enter fullscreen mode Exit fullscreen mode

Great, we have a Pinia state management system in our e-commerce store, next let's figure out how to create and use it.

2. Creating the First Pinia Store

We will create a new "store" folder in the root of our project, and inside that folder create a base.js file, this file will be our first storage and we will store over there our main data that needs to be available everywhere like modal and notification status or window width.

Next, we need to use the "defineStore" function to create a new store, and inside the defineStore function, we will pass an object as a parameter. That object will contain id as a unique store name, state as a callback function that will return stored values, actions as an object that will contain functions that can mutate stored values, and getters as an object that gives us access to our values.

In some cases, we will need the device window width which is why I suggest creating such a value in our first store. We will add "windowWidth" as our store value, "aWindowWidth" as our first action that will update "windowWidth", and "gWindowWidth" as our first getter that will return the "windowWidth" value.

import { defineStore } from 'pinia';

export const useBaseStore = defineStore({
    id: 'base',
    state: () => ({
        windowWidth: 1200
    }),
    actions: {
        aWindowWidth(payload) {
            this.windowWidth = payload;
        },
    },
    getters: {
        gWindowWidth() {
            return this.windowWidth;
        }
    }
})
Enter fullscreen mode Exit fullscreen mode

Now we will import the "base" store into the app.vue file and add a new event listener that will call action and update the "windowWidth" value. Also, do not forget to remove that event listener before leaving.

<script>
import { useBaseStore } from "./store/base";
export default {
  name: "App",
  computed: {
    baseStore() {
      return useBaseStore();
    }
  },
  methods: {
    updateWindowWidth() {
      this.baseStore.aWindowWidth(window.innerWidth);
      console.log(this.baseStore.gWindowWidth);
    }
  },
  mounted() {
    this.updateWindowWidth();
    window.addEventListener('resize', this.updateWindowWidth);
  },

  unmounted() {
    window.removeEventListener('resize', this.updateWindowWidth);
  },
}
</script>
Enter fullscreen mode Exit fullscreen mode

Let's rebuild our project and check the result.

Nuxt js implementing Pinia

Okay, looks great, we have a window width value and confirmation that our store was implemented successfully.

We have successfully established Pinia and launched our first store, laying the groundwork for effective state management in our Nuxt.js e-commerce platform. We'll go deeper into Pinia's features in the next articles and build extra stores to handle different parts of our e-commerce platform, such as product filtering or cart management.

The best variant to study something is to make it by your own, the same thing works with coding, but if you need a source code for this tutorial you can get it here.

Top comments (0)