Search code examples
javascriptvue.jspinia

Setting state with Pinia using Options API


I have this store defined in the options API:

import { defineStore } from "pinia";
import AxiosBeerOffice from "@/services/axiosBeerOffice";

const uri = {
  getNavbarItems: "/navbarItems",
};

export const useNavbarStore = defineStore({
  id: "navbar",
  state: () => ({
    navbarItems: [],
  }),
  actions: {
    getNavbarItems: async () => {
      const response = await AxiosBeerOffice.get(uri.getNavbarItems, true);
      const { data } = response;
      this.navbarItems = data;
    },
  },
});

The problem is when I call the getNavbarItems actions, the line that set the value to navbarItems throws me this error:

enter image description here

I really don't understand what is going on so any help will be appreciated.


Solution

  • The arrow functions doesn’t have their own bindings to this which explains the error with this.navbarItems. Try the below instead:

    
      actions: {
        async getNavbarItems() {
          // …
        },
      },
    
    

    Based on https://github.com/vuejs/pinia/discussions/1267. Also see examples from https://pinia.vuejs.org/core-concepts/actions.html