Search code examples
vuejs3piniavue-script-setup

Trying to get "board" from "boards" use Pinia getter and receive undefined


what do i wrong?

I try to get the name of the board from Pinia Store.

  1. I fetch the data from API onMounted in parent component (composition api setup):
onMounted(() => {
  boardStore.fetchBoards();
});

and store the data in Pinia Store:

 state: () => ({
    boards: [],
    activeBoardId: storage.getItem('activeBoardId') || null,
  }),
  actions: {
    async fetchBoards() {
      await apiClient
        .getBoards()
        .then((response) => {
          this.boards = response.data;

          return response;
        })
        .catch((err) => {
          return err.response.data;
        });
    },
  },
  getters: {
    getBoardById: (state) => {
      return (id) => state.boards.find((board) => board.id === id);
    },
    getActiveBoardId: (state) => {
      return state.activeBoardId;
    },
  },
  1. In my component i try to get the name from the board via getBoardById():
import { useBoardStore } from '@stores/boardStore';

const boardStore = useBoardStore();

let board = boardStore.getBoardById(boardStore.getActiveBoardId).name

I expect to get the name of the board from the Pinia Store, but receiving undefined.

i also tried to use computed:

let board = computed(() => boardStore.getBoardById(boardStore.getActiveBoardId));

and can see the values:

ComputedRefImpl {dep: undefined, __v_isRef: true, __v_isReadonly: true, _dirty: true, _setter: ƒ, …}
...
value: Proxy
    [[Target]]: Object
        ...
        id:  95
        name: "Privat"
        ...

But when i tried to use access i get undefined:

console.log(board)
console.log(board.name)
console.log(board.value)
console.log(board.value.name)

Also wehn i check Vue Dev Tools -> Pinia i see the "boards" Array with some items object. When i open one, i can see the "name":

boards:Array[2]
  0:Object
    ...
    id:95
    name:"Privat"
    ...
   1:Object
    ...
    id:97
    name:"Work"
    ...
activeBoardId:97

I suspect that either I'm trying to access them incorrectly or they're doing it too early, that the data has not yet hit the store, because async.

It's probably a small thing, but i can not find the bug or fix :-)



I expect to get the name of the board from the Pinia Store, but receiving undefined.

Solution

  • I found a solution, maybe not the best one, but it's work:

    onMounted(async () => {
      await boardStore.fetchBoards();
    
      setBoardName();
    });
    
    watch(
      () => boardStore.activeBoardId,
      () => setBoardName()
    );
    
    const setBoardName = () => {
      const board = computed(() => boardStore.getBoardById(boardStore.activeBoardId));
    
      resetForm({
        values: {
          name: board.value.name,
        },
      });
    };