Struggling to figure out how to save a single object instead of the whole array when creating a movie watchlist. Clicking "add to watchlist" should save the single object in LocalStorage, while clicking "remove from watchlist" should remove it. I've attempted to regulate this with methods, but something seems off. The data is sourced from an API request. Check out the code below:
<template>
<div>
<div class="card" v-for="movie in movies"
:key="movie.id">
{{movie.title}}
{{movie.release_date}}
<button type="submit" @click="storeMovie" >
Add
</button>
<button type="submit" @click="removeMovie">
Remove
</button>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
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®ion=IT')
.then(response => {
this.movies = 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) {
this.movies.push(this.movie);
localStorage.setItem("movies", JSON.stringify(this.movies));
this.movie = "";
}
},
removeMovie() {
localStorage.removeItem('movie');
}
},
}
</script>
<style scoped lang="scss">
</style>
Attempting to parse and stringify, but may be missing something. Also trying out methods that are not functioning as expected