Vue component fails to reflect changes in state update

<div v-for="(photon, key) in $store.state.notConnected" v-bind:key="key">
    <div v-if="!photon.connected">
        <p>Photon is not Connected</p>
    </div>
    <div v-if="photon.connected">
        <p>Photon is Connected</p>
        <b-btn v-on:click="showNewSetup(photon)>Setup</b-btn>
    </div>
    <div v-if="photon.showSetup">Setup Page</div>
</div>    

Store.js

export const store = new Vuex.store({
 state:{
   notConnected:{}
 },
 mutations:{
 setDevices(state,value){
 value.data.forEach(ele =>{
 state.notConnected[ele.id]={}
 state.notConnected[ele.id].showSetup=false
 state.notConnected[ele.id].connected=ele.connected
 }
 },
 SHOWNEWSETUP(state,value){
  state.notConnected[value.id].showSetup=true
}}
actions:{
async getDevices(context){
let devices = await axios.get('http:10.10.10.1:3000/api')
context.commit('setDevices',devices)
}
}
})

I have noticed a discrepancy between the updated state in my Vuex store and the rendering of components using v-if. Despite seeing the state mutation reflected in Vue DevTools, the setup page div does not update as expected. Interestingly, navigating to a different route and returning to the page triggers an update in the component.

Answer №1

Vue struggles to recognize modifications in Arrays (unless using vue3 with proxy capabilities).

To address this issue, it is recommended to adjust your mutation like so:

SHOWNEWSETUP(state,value){
  Vue.set(state.notConnected, value.id, {showSetup=true})
}

By doing this, Vue's reactivity system will be notified of the change, ensuring that everything functions as intended.

Answer №2

To optimize your component, consider using a computed property instead of directly accessing the state:

<template>
    <div v-for="(photon, key) in photons v-bind:key="key">
        <div v-if="!photon.connected">
            <p>Photon is not Connected</p>
        </div>
        <div v-if="photon.connected">
            <p>Photon is Connected</p>
            <b-btn v-on:click="showNewSetup(photon)">Setup</b-btn>
        </div>
        <div v-if="photon.showSetup">Setup Page</div>
    </div>   
</template>

<script>
    computed: {
        photons() {
            return this.$store.state.notConnected
        },
    }
</script>

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 methods can I use to prevent unauthorized access to my JavaScript files?

By using Minify, I am able to minify and cache all of my script requests. I want to restrict access for users to only the minified versions of JavaScript files. My Minify setup can be found at www.example.com/min, while my scripts are located at www.examp ...

Transferring information between a service and a controller

I'm struggling to pass data between a service and a controller in my AngularJS project. Even though I've followed the recommended steps, the code is not functioning as expected. Below is the controller snippet: function udpController($scope ...

Creating dynamic routes in react-router-dom using conditions

I'm currently developing an application using react-router-dom for navigation. I've encapsulated all my <Routes> inside a container provided by Material UI. However, I want my home page to be outside of this container so that I can display ...

Getting the ID from an array of objects in AngularJS: A How-To Guide

I need help with extracting the id from an array of objects in AngularJS. It seems like $scope.data.id is returning undefined. Can anyone spot what I may be doing wrong, or suggest a better way to achieve this? Data: [{"_id":"57e540ab352e81329c984aba","n ...

Unexpected Undefined Return in Request Parameters

Hey everyone, I'm currently working on setting up a mock API server using a JSON file with some dummy data. The first route I created is functioning perfectly: const express = require("express"); const router = express.Router(); const data = requir ...

Unexpected server failure due to a new error occurring in the asynchronous authentication login function

This problem is really frustrating... I'm having trouble with a throw exception that causes my express server to crash in my async login function. The issue here is that the error isn't caught by the try/catch block. Even though the user data is ...

Discrepancy in div height between Chrome/Edge and Firefox browsers

I am currently in the process of designing a straightforward website layout that includes a navigation bar at the top. The main focus is on an image that needs to stretch from the bottom of the navbar to the bottom of the window, filling up the entire scre ...

Images that float to the right can escape the boundaries of their div container

I'm struggling to find a solution for my current HTML setup. Here's what I have: <script> $(document).ready(function(){ $("#flip").click(function(){ $("#panel").slideToggle("slow"); }); }); </script> <style type="text/cs ...

Adjust the color of a DIV based on the text value retrieved from an external source

I am looking to dynamically change the text color between red and green based on a numeric value received from an external source (API). If the value is greater than or equal to 50, it should be displayed in red. If it's less than 50, then it should ...

Verifying the status following a promise execution in the initial promise function

Below is the function I am currently working with: startGame = () => { this.buildDeck() .then(this.shuffleDeck) .then(this.dealToPlayer) .then(setTimeout(this.dealToPlayer, 2000)) .then(setTimeout(this.dealToDealer, 4000)) } In ...

The MVC 5 view is unable to display an HTML image when adding it within an appended div

Currently, I am working with ASP.net MVC5 at a novice level. I'm faced with the challenge of creating a div that displays an image using a JavaScript function. Here is the code snippet I have: function showLoadingImage() { $('#submit_Em ...

What is the significance of "('_' + element + '_')" in coding?

function enlarge(element) { var target = document.getElementById(element); var currentHeight = target.offsetHeight; var scrollHeight = target.scrollHeight; var loopTimeout = setTimeout('enlarge(\'' + element + '&bso ...

Using the history.push() method from the Action Creator will update the URL without actually redirecting to a new page

I have a login page component that I've set up to redirect to another page after a successful login. However, even though the URL changes correctly, the page remains on the Login page. First, let me show you how I import the history module to be used ...

When using jQuery each method, it may return an [object Object]

Having an issue with the html variable displaying [object Object] instead of actual elements. Any suggestions on what I should change? var html = ''; $.each(data.response, function(index, value) { var tr = $('<tr>'); var ...

Instructions on including a directory in the package.json file for publication on npm

I am facing an issue when attempting to publish a module in the npm repository as it is not recognizing the 'lib' folder. Even though I have included it in the package.json file as shown below, the 'lib' folder contents are not being re ...

When using SweetAlert2, a single button will automatically be highlighted as soon as the modal opens

I recently made the switch from using SweetAlert to SweetAlert 2. It took some time to get used to, but I finally achieved my desired outcome, with one small exception. Upon opening the modal, if there is only one button and no other inputs, the button ap ...

What is the best way to add new key value pairs to the dictionary?

I am attempting to distinguish between single clicks (assigned value 0) and double clicks (assigned value 1), while also keeping a log of the click and its position in a map. However, I have noticed that the keys are automatically sorted in ascending order ...

Steps for setting all textareas on a website to "readonly" mode

My website contains numerous textareas but they currently do not have the read-only attribute. It would be very time-consuming to manually add the readonly attribute to each one. Is there a more efficient method to make all textareas read-only? ...

Ways to transmit data from PHP to JavaScript

I have a file called "hotlaps.php" where I've created a JavaScript script: echo "<body onload=\"myFunction(".$array_1.",".$array_2.",".$array_3.");\">"; In my "hotlaps.js" file, I have the following function: function myFunction(arr ...

What methods can I use to prevent repeated login requests to SalesForce databases when using Express.js routers?

Is there a way to avoid logging into SalesForce databases and passing queries on multiple routers in express.js? It's tedious to login every time. If you have any suggestions, please let me know. var conn = new jsforce.Connection({ oauth2 : salesfo ...