What is causing the local storage to not persist after refreshing the page?

Even after a browser refresh, the button text 'completed' should remain intact depending on whether the variable item is true (after the button click). I have experimented with Chrome and believe the issue is not related to the browser.

<template>
<button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
  {{ buttonText }}
</button>
</div>
</template>

<script>
export default {


item: '',
data() {

  return {
  item2: this.item
  }
},
methods: {
on_order_button_click() {
 this.item2 = true;
  localStorage.setItem(this.item2);
}

},
mounted() {
const storedState = localStorage.getItem(this.item2) === 'false';
if (storedState) {
  this.item2 = storedState;
}
},
computed: {
buttonText() {
  return this.item2 === true ? "Completed" : "Complete";
},
order_button_style() {
  return this.item2 === true
    ? "btn btn-danger"
    : "btn btn-primary";
}

}

};
</script>

Answer №1

localStorage.setItem requires two parameters, name and value.

The correct way to set an item in the localStorage is as follows:

localStorage.setItem('item', this.item2)

and to retrieve it:

localStorage.getItem('item')

Some suggestions on other sections of your code:

  • You can simplify this.item2 === true to just this.item2 if item2 will always be a boolean.

  • You are only using the value from localStorage when it is false, but since you only set it to true, this condition will never be met.

  • It's unclear what purpose the item property at the top level of the object serves.

  • Consider following global conventions by using camelCase for your method names.

UPDATE:

I believe this is what you intend to achieve:

on_order_button_click() { 
  this.clickedOrderButton = true;
  localStorage.setItem('clickedOrderButton', this.clickedOrderButton);
}


created() {
  this.clickedOrderButton = localStorage.getItem('clickedOrderButton') === "true";
}

I've changed item2 to clickedOrderButton for clarity. The use of 'item2' was confusing based on the provided code.

There's no need to check if clickedOrderButton is true before assigning it in this scenario.

Additionally, I replaced mounted with created as there is no requirement to wait until the component is mounted to execute this logic.

UPDATE#2:

If you have multiple instances of this component, consider using a unique identifier instead of clickedOrderButton. You can pass this identifier as a prop from the parent component.

For example:

props: {
  id: { type: String, required: true }
}
...
localStorage.setItem(`clickedOrderButton-${this.id}`, this.clickedOrderButton);
...
localStorage.getItem(`clickedOrderButton-${this.id}`);

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

Is it possible for JavaScript to create an object that, when accessed directly, will return a string or number, and when its property is accessed, it will return that

something like this: const object = { value: 'value', label: 'label' } object === 'value' // true, accessing it directly returns 'value' object.label === 'label' // true object.value === 'value&ap ...

The ng-scope class in AngularJS is failing to be applied

While exploring the Angular Tutorials, I noticed an interesting detail in their example where the ng-scope CSS class is added to each element with a directive. If you want to check out the tutorial for yourself, here's the link: Angular Tutorial on S ...

Safari and iOS 15 to 14 have rendered the Javascript audio context unusable

Recently, I noticed that the IOS/Safari upgrade has caused some issues with the web audio API. Check out this simple code that used to work on IOS and Safari before the upgrade, but now it doesn't work anymore. Interestingly, it still works on Firefo ...

Transferring JSON information from JavaScript to PHP using Jquery AJAX

Struggling to send JSON data from JavaScript to a PHP script using the code below. While debugging, "isRunning" initially shows true, indicating that AJAX is not running. However, when it moves to the next part of the AJAX code, "isRunning" changes to fal ...

Tips for dynamically inserting JSON data into HTML elements

{ "top10": [ { "state": "red", "claimed": true, "branch": "release-2.3.4", ...

Reveal or Conceal Information Depending on Cookie Status

Below is the Jquery code I am using: $("#tool").click(function() { $(".chelp").slideToggle(); $("wrapper").animate({ opacity: 1.0 },200).slideToggle(200, function() { $("#tool img").toggle(); }); }); When the #tool img is clicked, bot ...

Display and conceal multiple div elements using a timer

Currently, I am working on creating a message box that will display active messages one by one from a MySQL table. The challenge is that the number of divs needed can vary depending on the number of active messages in my database. Using an ajax timer and P ...

Is there a method in Kalendae js that automatically triggers the closing of the calendar after a date has been selected?

Currently, I am using Kalendae from https://github.com/ChiperSoft/Kalendae and I have to say it is fantastic. The best part is that I don't have to worry about dependencies. By default, the calendar pops up when a text box is selected and updates the ...

Showing the JSON server response on the client side without using JQuery

I'm working on creating a function that can retrieve JSON server responses and then display the content from the JSON in a list on a webpage without relying on JQuery. Is there a way to accomplish this task? filterGet: function () { var ajax ...

Best Practices for Managing Asynchronous Updates in Angular Controllers

Let me explain my current setup -- I have a controller that utilizes a service to perform some tasks and then fetches data asynchronously. Right now, the data is returned after a timeout, but ideally it would involve more complex operations: This is how m ...

The caption below the image is not functioning correctly when hovering over it

I'm having trouble getting the text to appear correctly underneath the image. Whenever I hover over the image, the text seems to overlap it. I am sure there is a simple solution to this issue, but I can't seem to figure it out. Removing the inlin ...

Strange Node.js Issue

I don't have much experience with node.js, but I had to use it for launching on Heroku. Everything was going smoothly until a few days ago when suddenly these errors started appearing. Error: /app/index.jade:9 7| meta(name='viewport', co ...

How can I update the state with the value of a grouped TextField in React?

Currently working on a website using React, I have created a component with grouped Textfields. However, I am facing difficulty in setting the value of these Textfields to the state object. The required format for the state should be: state:{products:[{},{ ...

Update database upon drag-and-drop using jQuery

I have a dataset (shown below) that undergoes sorting by 'section'. Each item is placed into a UL based on its section when the page loads. My goal is to automatically update the section in the database when a user drags an item to a different s ...

Is there a way to modify the colors of particles in GPUParticleSystem with Three.js?

I have encountered an issue where I am trying to add black particles in a white THREE.scene. Despite changing the spawn option color, there are still white particles present as if there is a base particle spawn color. The problem arises when I set a white ...

Using Vue.js to add animation effects to elements

What is the best way to use the .animate function on an element in vuejs? <aside v-transition v-if="toggleMenu"> <a href="#">Haha</a> <a href="#">Nice</a> <a href="#">Menu</a> </aside> A similar piece ...

Encountering issues while attempting to utilize pdf2json in a TypeScript environment

When attempting to import pdf2json (3.0.1) into my Node project using TypeScript, I encountered the following error: "Could not find a declaration file for module 'pdf2json'." I also tried installing @types/pdf2json for TypeScript but found tha ...

Invoking a function that is declared in a fetch request from an external source beyond the confines of the fetch itself

I am currently struggling with calling a function that is defined inside an API Fetch response function. My code sends an API fetch request to the GitHub API to retrieve a repository tree in JSON format. The problem arises when I try to call a function def ...

Is there a way to adjust this angular2 service to make it slightly more synchronous?

My goal is to create an Angular2 service that performs the following tasks: FTP to a remote server Read certain lines from a file Create a 'results' JSON object and return it to the component that called the service I have successfully impleme ...

Load elements beforehand without displaying them using a div

In order to efficiently manipulate my Elements using jQuery and other methods, I am exploring the idea of preloading them all first. One approach I have considered is creating a div with CSS display set to none, and placing all the elements I need for my w ...