I am looking to store individual objects in LocalStorage, however, I currently have the entire array saved

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&region=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

Answer №1

Here are a couple of key observations based on the code you provided :

  • If you intend to add a new movie using the input, the Add button should be placed outside the v-for loop.
  • In order to handle the removeMovie event, ensure that you pass the store ID from the template so that we can effectively filter out the desired item from the movies array.

Check out the Live Demo below :

new Vue({
  el: '#app',
  data: {
    movies: [],
    movie: ''
  },
  mounted() {
    // Mock data for demonstration purposes, actual data will come from API.
    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()">
      Add
    </button>
  </div><br>
  <div class="card" v-for="movie in movies"
       :key="movie.id">
    {{movie.title}}
    {{movie.release_date}}
    <button type="submit" @click="removeMovie(movie.id)">
      Remove
    </button>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes the slowness of onsubmit=" " function?

Initially, I had the following setup: HTML: <form onsubmit="return validate()"> ... <input type="submit" id="submit-button"/> </form> JS: function validate() { // Extensive validation process with regex and more... $(& ...

Developing a unique attribute using AngularJS

As a beginner in AngularJS, I am experimenting with creating directives to manipulate the background-color of a <div> based on specific conditions. I aim to write code like this within my view: <div effect-color="#2D2F2A">content here</div& ...

Assigning values to objects in Vue: setting data properties

I am working with a Vue.js app and attempting to update a value inside an object. Specifically, I want to change the 'name' value when the @change="onfilechangev" event occurs. Is there a way to achieve this, or is it not possible to update an ob ...

Tips for restricting User access and displaying specific sections of the menu

I have a component that utilizes map to display all menu parts. Is there a way to make certain parts of the menu hidden if the user's access rights are equal to 0? const Aside: React.FunctionComponent = () => { const[hasRight, setHasRight] = us ...

What is the best way to manage HTML code that is delivered through JSON data?

I am dealing with data from a JSON that is in HTML code format. I need to print it as HTML, but currently it is only printing as a string: "content": "More tests\u003cbr /\u003e\n\u003cbr /\u003e\n\u003cdiv class=&bso ...

The issue of inaccurate positioning and rotation in three.js is often attributed to problems with sprite

I'm attempting to generate a sprite with text without utilizing TextGeometry for improved performance. var fontsize = 18; var borderThickness = 4; var canvas = document.createElement('canvas'); var context = canvas.getContext('2d' ...

What is the best way to incorporate a fade in effect when a user clicks on a JavaScript dropdown menu?

I found a helpful code snippet on GitHub at this link which allowed me to easily create a dropdown menu. However, I wanted to add a Fade in and out effect when the menu is clicked. Here is my attempted implementation, but unfortunately, the fadeIn functi ...

`Using Twitter Bootstrap in mobile app development with javascript`

I have been utilizing Twitter Bootstrap 2.3 on one of my websites and I appreciate its responsiveness and use of media queries for mobile devices. However, I have noticed a lack of mobile-specific features, particularly linked listviews. In order to addres ...

Is incrementing x by 1 equivalent to x + 1?

I have a very basic angular application. It simply increases the value by 1 when clicked on using ng-click. Take a look at JSFiddle <div ng-app="app" ng-controller="ctrl"> <div ng-click="hello=hello+1">THIS WORKS ON CLICK: {{hello}}</d ...

The React component fails to inherit any props that are passed to it when it is rendered using a logical operator

I'm facing an issue with a component that doesn't seem to receive any props when I use a logical operator in conjunction with it. Oddly enough, if I render the component without the conditional statement, everything works fine. But as soon as I a ...

Is there a way to prevent a page from rendering until the necessary data is retrieved?

I am facing an issue where my page is attempting to render before the data is available. I have used async/await in my code, but I keep getting an error saying that the data is undefined. Interestingly, when I comment out the page elements and check the Re ...

Setting the height of columns in a Bootstrap panel to 100%

Is there a way to achieve 100% height for all three columns even without content? Check out this JSFiddle: <div class="row"> <div class="col-md-12"> <div class="shadow panel panel-default"> <div class="blue white-bord ...

Testing a directive that contains a parent directive declaration is essential in ensuring proper functionality within an

I recently developed a utility tool for my application called batch-checkbox-util.js and I am eager to conduct some tests on it. Although I have written a test script, which can be found at the same link provided, I am encountering an issue during the tes ...

Unable to Submit Form in JSP Page

I have encountered an issue with a JSP page that contains a form which I am submitting using JavaScript. When the page has a smaller number of items, between 10-50, the submission works perfectly fine. However, when there are around 500 items or more on t ...

Changing the text color of the Vuetify Table header is a simple way to customize the

I am currently working on a Vuetify table with the class condition-table. I have applied the following CSS styling: .condition-table { background-color: #e1f5fe70; } The styling seems to work fine so far. However, when I added this additional CSS: .co ...

Is there a way to remove the row after hitting its corresponding button?

Having trouble working with table tags in a cshtml page, particularly when appending tr and td elements using ajax. I'm unsure of how to delete a row when it's clicked on and also how to retrieve the values of inputs within each row. /// <r ...

The server experiences crashing issues when attempting to retrieve data from Mangodb for the second or third time

This is the code I have written in VS Code. const express=require("express"); const app= express(); const mongoose=require("mongoose"); const Listing=require("./models/listings"); const path=require("path"); const me ...

Alter the jQuery in an Iframe to make changes to the parent document

Exploring a unique use case where I am sandboxing multiple JavaScript libraries into hidden iframes. Within the website, there are various widgets, all sourced from the same domain, that might require different versions of JS libraries. To avoid global con ...

The initial click does not trigger a state update in React

I attempted to create a straightforward system for displaying data with two sorting buttons (ascending & descending). My approach involved fetching and displaying data from an array using the map method. In a separate component file, I utilized useEffect ...

Limit the velocity of an object in Box2D using JavaScript

In my Box2D simulation, a collection of dynamic objects is experiencing various random forces. Is there a way to set a maximum speed for each object (both translational and rotational)? I considered implementing a workaround, but I'm curious if the e ...