be able
be able

Reputation: 81

Pinia | Vue3 - Accessing array in deep object

In Pinia (base.js)

export const useBaseStore = defineStore('base', {
  state: () => {
    return {
      areaLocal: [
        { id: 0, name: 'LAX' },
        { id: 1, name: 'SFO' },
        { id: 2, name: 'SAN' },
      ],
      areaLocal2: {
        area: [
          { id: 0, name: 'AAA' },
          { id: 1, name: 'BBB' },
          { id: 2, name: 'CCC' },
        ]
      },
    }
  },
  getters: {
    getAreaById: (state) => {
      return (areaId) =>
        state.areaLocal.find((areaLocal) => areaLocal.id === areaId)
    },
    // ...
  }
})

in Vue (area.vue)

<script setup>
import { computed, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useBaseStore } from '../stores/base'

const areaStore = useBaseStore()
const { getAreaById } = storeToRefs(areaStore)
const areaIndex = ref(0)
</script>
<template>
    <div class="container">
        <h2>AREA: {{ getAreaById(areaIndex).name }}</h2>
....

This, areaLocal, I get "AREA: LAX", which is correct, but HOW I can write "getter" in the pinia for access to "areaLocal2", the object "area" then the array?

state.areaLocal2.area.find((areaLocal2.area) => areaLocal.id.area === areaId

The above throws an undefined error.

Upvotes: 2

Views: 2584

Answers (1)

Riza Khan
Riza Khan

Reputation: 3158

getArea2ById: (state) => (areaIa) => state.areaLocal2.area.find((area) => area.id === areaId)

You are already in area by the time you hit the find higher order function so no need to reference it again inside of it.

Upvotes: 1

Related Questions