A Vue.js component modifies one store state variable but leaves another unchanged

Currently developing a Vue 3 application that utilizes Vuex and the Composition API.

Encountered an issue while working on it.

A component is supposed to display elements based on the state of two store variables. One is an array, and the other is a boolean. The array updates correctly, but the boolean does not.

Here's the code for the store:

export default {
    state() {
        return {
            current: {
                chat: {
                    them_writing: false,
                    texts: []
                }
            }
        }
    },
    mutations: {
        add_text_to_chat(state, text) {
            state.current.chat.texts.push(text);
        },
        set_them_writing(state, v) {
            state.current.chat.them_writing = v;
        }
    }
};

And here's the component code:

<template>
  <div v-if="them_writing || shown.length">

    <div class="text_wrapper" v-for="(text, index) in shown" :key="index">
      <div class="text">
        {{ text.content }}
      </div>
    </div>

    <div class="text" v-if="them_writing">
      <span>.</span>
      <span>.</span>
      <span>.</span>
    </div>
  </div>
</template>

<script setup>
import {  inject, ref } from "vue";

let store = inject("$store");

const shown = ref(store.state.network.current.chat.texts);
const them_writing = ref(store.state.network.current.chat.them_writing);
</script>

<style scoped>
</style>

After calling the add_text_to_chat mutation, the elements list updates as expected.

However, when using set_them_writing with a new value, the UI doesn't reflect the change.

Since the first variable is reactive, I believe the issue lies elsewhere.

The code setting seems consistent, so why is just one value not updating? Any insights?

Answer №1

Your current code utilizes the Composition API in Vue 3 along with Vuex for state management.

The problem you're encountering, where one state variable updates correctly while the other does not, may be due to reactivity issues.

When you set up shown and them_writing using ref(store.state.network.current.chat.texts) and ref(store.state.network.current.chat.them_writing), these references are only established once during component initialization, so they won't automatically update when there are changes in the Vuex store state.

As a result, shown might not reflect updates accurately.

To ensure that shown and them_writing reactively respond to changes in the state variables, it's recommended to use computed properties instead.

Below is an updated script setup that demonstrates how to achieve this:

<script setup>

import { inject, computed } from "vue";

let store = inject("$store");

const shown = computed(() => store.state.network.current.chat.texts);
const them_writing = computed(() => store.state.network.current.chat.them_writing);

</script>

By leveraging computed properties, shown and them_writing will dynamically update whenever the related Vuex state variables change, effectively resolving the issue of inconsistent UI updates.

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

Using Node.js and Express to import a simple JavaScript file as a router

Can anyone help me understand how to import the user.json json file into my user.js? I want the json file to be displayed when typing /user but I'm struggling with the new version of Node. index.js import express from 'express'; import body ...

Performing calculations within handsontable

Trying to figure out how to concatenate values from a handsontable grid, I stumbled upon some code on jsfiddle that caught my eye. Here is the link: http://jsfiddle.net/9onuhpn7/4/ The task at hand involves 3 columns A,B,C and an attempt to concatenate ...

The Google Chrome console is failing to display the accurate line numbers for JavaScript errors

Currently, I find myself grappling with debugging in an angular project built with ionic framework. Utilizing ion-router-outlet, I attempt to troubleshoot using the Google Chrome console. Unfortunately, the console is displaying inaccurate line numbers mak ...

How can I retrieve elements i from each array in HandlebarsJS and then access element j, and so on?

Given a JSON like this: { "network": [ { "name": [ "John", "Jill", "June" ] }, { "town": [ "London", "Paris", "Tokyo" ] }, { "age" : [ "35", "24", "14" ] } ] } Unfortunately, my data is in this format and I have to work w ...

My search field in Safari (desktop) doesn't respond to jQuery's .focus() function

My website has a hidden search field that appears when the user clicks on the search icon. I want to automatically bring focus to the search input so users do not have to click twice. This feature works perfectly in Chrome, but not in Safari (desktop). I t ...

Switching Unicode icon when element is clicked

My form has two inputs - one for text input and the other for submitting, like a button. I have added an icon to the submit button and want it to change when clicked. <input class="searchBtn" id="submit" name="submit" type="submit" value="&#xf002"& ...

The watcher fails to function properly when attempting to pass data from a for loop in the parent component

<div v-for= "(item , index) in chartData" class="col" :key="index"> <ColumnChart :chartdata="item.tactical" :simpletype="true" /> </div> One of the properties I have is called chartData, initially set as an empty array. Upo ...

What is the best way to customize the styles of a reusable component in Angular2?

I am working with a reusable component called "two-column-layout-wrapper" that has its styles defined in the main .css file. In another module, I need to use this component but customize the width of two classes. How can I override these styles? import ...

Tips for including parameters in the existing URL using AngularJS

I used the $location.url() method to obtain my current URL. $location.url() returns '/details' Now, I am looking to append some parameters, such as '/details/student' How can I add '/students' to my current URL upon a ...

onpageshow event behaves as expected exclusively on webkit browsers (triggers function solely when visible on the screen)

I am inserting an HTML file using an object tag. The encompassing div of the object tag is hidden with a display:none property. However, I encounter an issue where the onpageshow event that I placed on the body tag of the HTML object behaves differently a ...

Tips for managing Vue component content prior to data being fully loaded

I'm currently integrating product category data from Prismic into my Nuxt project and seeking guidance on best practices. Specifically, I need clarity on managing the state when data is still being fetched and there's no content to display in the ...

Issue with pop-up functionality on web page using HTML, CSS, and JavaScript

Recently, I created a unique popup using HTML. You can see the complete code (excluding CSS) here: https://codepen.io/nope99675/pen/BawrdBX. Below is the snippet of the HTML: <!DOCTYPE html> <html> <head> <meta charset=&quo ...

What is the best way to dynamically adjust the size of a grid of divs to perfectly fit within the boundaries of a container div without surpassing them?

Currently, I am working on a project for "The Odin Project" that involves creating a web page similar to an etch-a-sketch. I have made some progress, but I am facing a challenge with dynamically resizing a grid of divs. The issue lies with the container d ...

A step-by-step guide to adding a checkbox column dynamically within handsontable

I am currently utilizing handsontable within a jsfiddle at http://jsfiddle.net/kc11/cb920ear/1/. My task involves dynamically inserting a checkbox column before the existing data. The structure I am working with appears to be a multidimensional array, as s ...

Eliminate disparity in Woocommerce shopping cart

I have a pizza with various toppings. When the user selects "Add Toppings," they appear as drop-down options defaulted to "none." I want to hide the selected "none" options in the cart and checkout. Although I've successfully hidden them on the cart ...

Alternative for Jquery: a new Hash Table solution using Prototype JS

Greetings everyone! I have experience as a prototype JS developer but now I am transitioning to jQuery for work/client reasons. One feature I really liked in Prototype was the Hash class, such as var h = new Hash();. However, I understand that jQuery doe ...

Exploring Checkbox Limiting with jQuery

Is there a more efficient approach to restrict the selection of checkboxes? I want the script to be adaptable depending on the applied class, which will always indicate the maximum allowed value (e.g., "limit_1" or "limit_2"). Currently, I'm creatin ...

Is it necessary to release a new library version for non-functional updates?

As the maintainer of several JavaScript libraries, I often find myself needing to update dependencies that don't necessarily require any functional changes. This is especially true when my library is not impacted by a breaking change in one of its dep ...

Is it feasible to generate a fixed lighting effect overlay with HTML and CSS?

Is it possible to incorporate a static lighting effect overlay using HTML/CSS? My project consists of an HTML5/JS app with a top navigation bar and a series of cards that are transitioned through using swipe gestures. These cards are displayed in gray ove ...

The significance of Token Details in Tokbox

I'm currently working on developing a video chat platform that caters to various user roles - some may just observe while others actively participate in calls. I've been exploring the capabilities of the Tokbox Api () which allows metadata to be ...