Search code examples
typescriptvue.jslocal-storagepinia

Vue 3, overwriting array after refreshing the page


App.vue

<script lang="ts">
import { defineComponent, computed, ref, watch } from 'vue';
import { useFilesStore, } from './stores/files'
import { marked } from "marked"

export default defineComponent({
  name: 'App',
  components: {},

  setup() {
    let store = useFilesStore()
    const storage = window.localStorage
    const createFile = store.createFile
    const markdown = ref<string>('')
    const currentLocalStorage = JSON.parse(storage.getItem("files") || "")

    if(!storage.getItem("files")) {
      storage.setItem("files", JSON.stringify(store.files))
    }
  
    watch(store.files, (files) => {
      storage.setItem("files", JSON.stringify(files))
    }, {deep: true});

    const markdownToHtml = computed(() => {
      return marked.parse(markdown.value)
    })

    return { store, markdownToHtml, markdown, createFile}
  }
});
</script>

<template>
  <div class="files">
    <button class="newFile" @click="createFile()">+ new File</button>
    <p v-if="!store.files.length">No files saved</p>
    <div v-if="store.files.length">
      <div v-for="file in store.files" :key="file.id">
        <h1>ID: {{ file.id }}</h1>
        <h2>Document: <input type="text" v-model="file.name"></h2>
        Content: <textarea type="text" class="html-content" v-model="markdown">
        </textarea>
        <p v-html="markdownToHtml"></p>
      </div>
    </div>
  </div>
</template>

store/files.ts



import { ref } from "vue"
import { defineStore } from "pinia"
import { nanoid } from "nanoid"
import Files from "../types/Files"

export const useFilesStore = defineStore("files", () => {

  const files = ref<Files[]>([])
  let currentFile = (null)

  async function createFile() {
    const newFile = {
      id: nanoid(),
      name: "new_document.md",
      date: new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }),
      content: ""
    }
    files.value.push(newFile)
    currentFile = newFile
  }  

  return { files , createFile, currentFile }
})

I'm using pinia and typescript. Thank you in advance for your help.

I understand what I need to do, but I don't know how to fix it. I've seen solutions in vanilla javascript, but they didn't work as I wanted.I have this currentLocalStorage variable, just don't know where and how to use it.


Solution

  • Turns out I found the bug myself, and it was basically stupid. I was setting the "files" value each time instead of assigning it to a variable from localStorage.

    if(storage.getItem("files")) {
      store.files = JSON.parse(storage.getItem("files") || "")
    }