2

I am trying to set values in a map stored in a pinia store (persisted into localstorage)

in this minimal (non) working example pushing elements into a list works fine but adding a element into a Map does not persist.

component.vue

<script setup lang="ts">
import { useStore } from "./store"

const store = useStore()
</script>

<template>
  <main>
    <button
      @click="store.createA"
      >
      Create new Array item
    </button>
    <ul v-if="store.array.length > 0">
      <li v-for="(item) in store.array">
        {{ item }}
      </li>
    </ul><br/>
    <button
      @click="store.createO"
      >
      Create Map Object
    </button>
    <ul v-if="store.mapObj.size > 0">
      <li v-for="(item) in store.mapObj">
        {{ item[1] }}
      </li>
    </ul>
  </main>
</template>

store.ts

import { defineStore } from "pinia"

export const useStore = defineStore({
  id: "character-manager",
  state: () => ({ array: [] as Array<{key: string, value: string }>,
                  mapObj: new Map() as Map<string,string>}),
  actions: {
    createA() {
      this.array.push({key: "key", value: "value"})
    },
    createO() {
      this.mapObj.set("key", "value")
    },
  },
  persist: {
    enabled: true,
    strategies: [{ storage: localStorage }],
  },
})
epsilonhalbe
  • 15,637
  • 5
  • 46
  • 74

0 Answers0