Home > Software design >  how can I get the data from localStorage to show in homePosts vue.js compositions API
how can I get the data from localStorage to show in homePosts vue.js compositions API

Time:11-10

I'm doing a simple blog app to practice vue.js. I'm using composition API. I have stored data that get filled in in a form. This data I want to print out in another component homePosts where you can see the written blogpost with writer, headline and blogtext. I have used v-model, stored data to localStorage, in homePosts I have used v-for and {{ }} syntax to get data. But nothing shows in homePosts.
Can someone please see what im missing.

writePost.vue

    <template>
      <div>
        <form >
          <label for="writer">Writer name: </label>
          <input v-model="newWriter" type="text" max="500" />
          <br />
          <label for="img">Select image:</label>
          <input type="file" id="img" name="img" accept="image/*" />
          <br />
          <label for="headline">Headline </label>
          <input v-model="newHeadline" type="text" max="500" />
          <label>Your blogtext: </label>
          <textarea v-model="newNote" name="" id="" cols="30" rows="30"></textarea>
          <button type="submit" @click="addNote" ><router-link to="/homePosts" >Post blog</router-link></button>
        </form>
      </div>
    </template>

    <script setup>
    import { ref } from "vue";
    
    const newNote = ref("");
    const newWriter = ref("");
    const newHeadline = ref("");
    const notes = ref([]);
    
    
    const addNote = () => {
      notes.value.push({
        id: Math.floor(Math.random() * 1000000),
        text: newNote.value,
        writer: newWriter.value,
        headline: newHeadline.value,
      });
    
      addLocalStorage(notes)
    
    };
    const addLocalStorage = (notes) => {
        
        localStorage.setItem("notes", JSON.stringify(notes))
        JSON.parse(localStorage.getItem("notes"));    
    }
    </script>

homePosts.vue

    <template>
    <div >
        <h1>Blog Posts</h1>
        <div  > 
            <div   v-for="note in notes" :key="note.id">
                <!-- <img  src="@/assets/person1.jpg"> -->
                <p > {{ note.writer }}</p>
                <p > {{ note.headline }}</p>
                <p  > {{ note.text }}</p>
            </div>
        </div>
    </div>
    </template>
    
    <script>
     export default {
        name: 'homePosts'
     }
     
    </script>

CodePudding user response:

You need to start your ref already parsing the existing items in your localStorage.

const notes = ref(JSON.parse(localStorage.getItem('notes') ?? '[]');

Or better yet, use a computed getter/setter:

const notes = computed({
  get: () => JSON.parse(localStorage.getItem('notes') ?? '[]'),
  set: (value) => {
    localStorage.setItem('notes', JSON.stringify(value))
  }
});

Or even better, take a look at vueUse/useLocalStorage

  • Related