Home > Back-end >  I need to save single objects in LocalStorage, but i have the whole array saved
I need to save single objects in LocalStorage, but i have the whole array saved

Time:12-07

I don't get how i am supposed to save only a single object a not the whole array. I am trying to create a movie watchlist. If I click "add to watchlist", the single object should be saved in LocalStorage. If I hit remove from watchlist, the object should get removed. I tried to write down methods to regulate all of that, but i guess somethings wrong. The data comes from an API request. Here's the code:

<template>
    <div>
        <div  v-for="movie in movies"
            :key="movie.id">
            {{movie.title}}
            {{movie.release_date}}
            <button type="submit" @click="storeMovie" >
                Aggiungi
            </button>
            <button type="submit" @click="removeMovie">
                Rimuovi
            </button>
        </div>
        
    </div>
</template>

<script>
import axios from 'axios'

    export default {
    //Cambiare il nome con quello del componente creato
        name: 'HomeComp',
        data () {
            return {
                movies: [],
                movie: "",
            }
        },
        mounted () {
            axios
                .get('https://api.themoviedb.org/3/movie/popular?api_key=###&language=it-IT&page=1&include_adult=false&region=IT')
                .then(response => {
                    this.movies = response.data.results
                    // console.log(response.data.results)
                })
                .catch(error => {
                    console.log(error)
                    this.errored = true
                })
                .finally(() => this.loading = false)

                if (localStorage.movies) {
                    this.movies = JSON.parse(localStorage.movies);
                }
        },
        watch: {
            movies: {
                handler(newMovies) {
                    localStorage.movies = JSON.stringify(newMovies);
                },
                deep:true
            }
        },
        methods: {
            getMovie() {
                this.movies = JSON.parse(localStorage.getItem("movie"));
            },
            storeMovie() {
                if (this.movie.length) {
                    // push the new movie to list
                    this.movies.push(this.movie);

                    // store the data in localStorage
                    localStorage.setItem("movies", JSON.stringify(this.movies));

                    // clear the input
                    this.movie = "";
                }
            },
            removeMovie() {
                localStorage.removeItem('movie');
            }
        },
    }
</script>

<style scoped lang="scss">
/*Inserire style componente*/
</style>

tried to parse ad stringify, but i think i'm doing it wrong in some way. Also written some methods, not working

CodePudding user response:

Few observations as per the code you posted :

  • As you want to store the new movie through input, Aggiungi button should come outside of v-for loop.
  • For removeStore event, You need to pass the store id from a template so that we can filter out the movies array.

Live Demo :

new Vue({
  el: '#app',
  data: {
    movies: [],
    movie: ''
  },
  mounted() {
    // This data will come from API, Just for a demo purpose I am using mock data.
    this.movies = [{
        id: 1,
      title: 'Movie A',
      release_date: '06/12/2022'
    }, {
        id: 2,
      title: 'Movie B',
      release_date: '07/12/2022'
    }, {
        id: 3,
      title: 'Movie C',
      release_date: '08/12/2022'
    }, {
        id: 4,
      title: 'Movie D',
      release_date: '09/12/2022'
    }, {
        id: 5,
      title: 'Movie E',
      release_date: '10/12/2022'
    }]
  },
  methods: {
    storeMovie() {
      const newMovieID = this.movies.at(-1).id   1;
        this.movies.push({
        id: newMovieID,
        title: this.movie,
        release_date: '06/12/2022'
      }) 
    },
    removeMovie(movieID) {
        this.movies = this.movies.filter(({ id }) => id !== movieID)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>
    Add new movie : <input type="text" v-model="movie"/>
    <button type="submit" @click="storeMovie()">
      Aggiungi
    </button>
  </div><br>
  <div  v-for="movie in movies"
       :key="movie.id">
    {{movie.title}}
    {{movie.release_date}}
    <button type="submit" @click="removeMovie(movie.id)">
      Rimuovi
    </button>
  </div>
</div>

  • Related