Daniele Tentoni
Daniele Tentoni

Reputation: 310

Pinia undefined state inside computed property

I try to use Pinia with composition Api and define store like:

export const useOfficeStore = defineStore("office", () => {
  const rooms = ref(new Map());
  rooms.value.set("first", {
    id: "first",
    width: 20,
    height: 20,
    top: 0,
    left: 0,
    pers: null,
  });
  const freeRooms = computed(function (state) {
    console.log("Invoked free rooms", state);
    return this.rooms;
  });
  return {
    rooms,
    freeRooms,
  };
});

In my component I import the state like this:

import { useOfficeStore } from "@/stores/counter";

const store = useOfficeStore();

function mark() {
    console.log("Free", store.freeRooms);
}

When I call the computed property, I face those logs:

Invoked free rooms undefined
Free undefined

What I'm doing wrong?

Upvotes: 0

Views: 3161

Answers (1)

TymoteuszLao
TymoteuszLao

Reputation: 954

You are getting undefined because you are mixing two syntaxes. Here is the example from the pinia docs:

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }

  return { count, increment }
})

In the case of composition API you can't use this to access state properties and the computed functions do no longer get state as the argument. So in your case the function should look like this:

const freeRooms = computed(function () {
  console.log("Invoked free rooms");
  return rooms.value;
});

Upvotes: 2

Related Questions