Issue with VueJS where changes made to properties in the mounted hook do not properly trigger the

I'm working on a VueJS component that features a button with computed properties for its class and text. These properties change every time the button is clicked, updating smoothly with each interaction. However, I've encountered an issue when attempting to persist this state in localStorage. Although the value of 'ordered' is being updated correctly, the button's text and class are not reflecting the changes in the UI after a page reload. Can anyone offer suggestions on what might be causing this discrepancy? Below is the relevant source code:

<template>
  <div class="main-view">
    <button type="button" :class="order_button_style" @click="on_order_button_click()">
      {{ order_button_text }}
    </button>
  </div>
</template>

<script>
export default {
  name: "FoodComponent",
  props: {
    item: Object
  },
  methods: {
    on_order_button_click() {
      this.item.ordered = !this.item.ordered;
      localStorage.setItem(this.item.id, this.item.ordered);
    }
  },
  mounted() {
    var storedState = localStorage.getItem(this.item.id);
    if (storedState) {
      this.item.ordered = storedState;
    }
  },
  computed: {
    order_button_text() {
      return this.item.ordered === true ? "Ordered" : "Order";
    },
    order_button_style() {
      return this.item.ordered === true
        ? "button ordered-button"
        : "button unordered-button";
    }
  }
};
</script>

Answer №1

When retrieving data from local storage, it is important to note that you will receive a string value. In the mounted lifecycle hook, the ordered property might be stored as a string instead of a boolean, causing the condition for the order_button_text computed property to never evaluate to true. To resolve this issue, you can simply convert the storedState property to a boolean:

 mounted() {
    const storedState = localStorage.getItem(this.item.id) === 'true';
    if (storedState) {
      this.item.ordered = storedState;
    }
  },

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

Locating the source of the function call within a file in Node.js

Is it possible to determine the location of a file if a method from a module is called within that file? For example: // my-module.js module.exports = { method: function () { // I would like to know the path to my-app.js here } } // my-other-mod ...

Updating the value of the chosen drop down option upon selection

I currently have a Material UI dropdown menu implemented in my project. My goal is to use the selected option from the drop down menu for future search functionality. How can I utilize onChange() to store the selected option effectively? At the moment, I ...

Accessing Facebook through Login with only a button visible

I need help with checking the user's login status on Facebook. I have implemented the code provided by Facebook, but all I see is the login button. How can I determine if the user is already logged in or not? function testAPI() { console.log(&apo ...

Issue with BlobUrl not functioning properly when included as the source in an audio tag

I need help with playing an audio file on click. I tried to implement it but for some reason, it's not working as expected. The response from the server is in binary format, which I decoded using base64_decode(responseFromServer); On the frontend (Vu ...

What steps can be taken to troubleshoot issues with the jquery mask plugin?

I am using the jQuery Mask Plugin available at to apply masks to input fields on my website. Currently, I am trying to implement a mask that starts with +38 (0XX) XXX-XX-XX. However, I am facing an issue where instead of mandating a zero in some places, ...

Images are failing to show up in the iPhone design

Encountering issues with displaying images on an iPhone? You can replicate the problem by minimizing your browser window horizontally. Here is a link showcasing the problem: here. To temporarily fix this, try zooming out the browser (Ctrl+-). You can see a ...

Leveraging Vue 3 Composition API with accessors

I'm currently in the process of refactoring some of my components using the composition API. One component is giving me trouble, specifically with asynchronous state when trying to retrieve data from one of its getters. Initially, the component was u ...

Exploring JSON Data with Mustache Templates

Dealing with a significantly large JSON object that I can't control, I'm struggling to output a list of records (related to people in this case) using Mustache.js. Despite simplifying the complex object into a more manageable one with just the ne ...

What are the steps to host a VueJS 3 application from subdirectories using NGINX?

I am facing a challenge in serving multiple VueJS 3 apps from the same NGINX server but from different subfolders. Despite exploring various resources on stack and the web, I have not been able to make things work seamlessly. In total, I have three apps e ...

Ensure that the alert for an Ajax JSON record count remains active when the count is

Trying out Ajax JSON for the first time has been a bit tricky. Even though I hard coded "Record: 1" on the server side, it keeps alerting me with a total record of 0. I'm not sure where I went wrong. Could it be an issue with how I passed the array da ...

How to conditionally enclose a group of components in a div using VueJS

I am working with a ref variable that has a specific structure: [ { "row": 1, "column": 1 }, { "row": 1, "column": 2 }, { "row": 1, "column": 3 }, { "row": 1, "column": 4 }, { ...

Enhancing URLs with jQuery/AJAX: A Comprehensive Guide to Adding Parameters

Whenever I try to use the get method on an HTML form, the submitted data automatically appears in the URL. You can see what I mean here. Interestingly, when attempting to achieve the same result with JQuery and AJAX using the get method, the data doesn&apo ...

Steps to create a typewriter effect using a collection of words

I managed to create a looping typewriter effect, but I'm facing an issue where the first word in the array is not being typed again after the first cycle. Additionally, I am seeing 'undefined' displayed after the last word before it repeats ...

Executing a Java program within a Docker container with the help of dockerode

I'm looking to send Java code as a string to an API for execution in a Docker container and then retrieve the console output. While I have successfully done this with Python, the process is different for Java since it needs to be compiled before runni ...

Using Vuex as a global event bus ensures that all subscribers will always receive notifications for

For a while now, I have relied on a global event bus in Vue - creating it as const bus = new Vue(). It works well, but managing subscriptions can get tedious at times. Imagine subscribing to an event in a component: mounted() { bus.$on('some.event ...

The issue of linking .then() functions

I've been struggling to grasp the concept of Promises/then-ables for a while now. Currently, I am working with NextJS. My goal is to chain together the following steps: Retrieve data from an API Save the data Modify the data to create a component (w ...

How can I retrieve and dismiss vee-validate errors from within a Vue component without direct access to the Vue instance?

I am having trouble clearing errors after closing a modal or sending data to the database outside of the Vue instance. I have tried using vm.$validator.errors.clean() and reset but they are not working for me. Do you have any suggestions on how to access t ...

I'm having trouble getting the JADE tag to render in Express script. Can anyone help me

I am trying to include client-side script in my JADE template and so far I have: extends layout script. function collect_data() { var transitions = {}; $( ":checkbox:checked" ).each(function (index, element) { //// some code ...

Verify ownership information by utilizing Node.js

Seeking guidance here. Currently, I am working on a Node.js and MongoDB application related to Apartment ownership. Within this application, there are two main datasets: Ownership and Tenants. For instance, Mr. A owns units 10 and 11. Then we have Mr. C wh ...

Certain individuals are experiencing difficulties accessing my Google application

I have created a node.js application with a Google login feature using the following packages: "passport": "^0.3.2" "passport-google-oauth": "^1.0.0" However, I am facing an issue where only a few users are able to access this feature. Below is the code ...