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

Angular: The property '**' is not found on the type 'Object'

Not too long ago, I embarked on a new Angular project where my setup involves Angular (the front-end) communicating with a node.js server (the back-end), which in turn might make requests to an api server or a mongo database when necessary. The tricky par ...

Adding HTML elements to a button using an array: a step-by-step guide

In the process of developing a web application feature using JavaScript, I have come up with a simple plan: Place a button in the bottom left corner. The button should only become visible after scrolling begins. Upon clicking the button, a new window wil ...

How can one implement closure in Angular 4?

I am looking to implement a nested function within another function in Angular 4 for closure. However, when attempting the code below, I encounter an error stating "cannot find name innerFn" outerFn(){ let a = "hello"; innerFn(){ console.log(a ...

Encountering Internal Server Error when running Node-Express app on render.com with query parameters live

Currently, I am facing an issue while attempting to execute a live route with query using my nodejs express application on render.com. Strangely, all other routes connected to the crud operations are functioning properly except for the search filter route ...

Issue with Canvas.doDataUrl not functioning properly in presence of an image on canvas

It seems like the code I have tried only works for local images. Can someone share a working code snippet for this? Here is what I've attempted: var base_image = new Image(); base_image.src = ("/img.png"); base_image.onload = function(){ var co ...

Using Jquery to Redirect Users According to URL Position

My current dilemma involves... I want to create a condition where if the URL specifically contains /foldername/index.htm or /foldername/ on mydomain.com, then it should redirect to http://www.example.com If the URL includes any URL parameter with /folder ...

Creating Comet applications without the need for IFrames

Currently embarking on my journey to develop an AJAX application with server side push. My choice of tools includes Grizzly Comet on Glassfish V2. While exploring sample applications, I've noticed that most utilize IFrames for content updates on the c ...

Override existing Keywords (change false to true)

Are there any ways to overwrite reserved words? It's not something I would typically consider, but it has sparked my curiosity. Is it feasible to set false = true in JavaScript? I've come across instances on different websites where individuals ...

Using TypeScript to send state through history.push({...})

I recently utilized the history.push method to redirect to a specific URL while passing along some information through the included state. Here's how I implemented it: const history = useHistory() history.push({ pathname: '/someurl/', ...

Using Vue.js to set both v-model and v-bind:value on one input element

I have a React component that has a form for submitting user information. The main issue I'm facing is setting a default value in the input field. When the page loads, I want the input field to display the user's existing email address by defaul ...

Identify when the user clicks on the URL bar or types in the browser's address bar using Jquery or JavaScript

In my current project, I'm faced with the challenge of interacting with the browser's URL bar. Specifically, I need to detect events using jQuery/JS when a user clicks on the address bar, types in it, or switches tabs. Is there a way to achieve t ...

What is the alternative method of sending a POST request instead of using PUT or DELETE in Ember?

Is there a way to update or delete a record using the POST verb in Ember RESTAdapter? The default behavior is to send json using PUT or DELETE verbs, but those are blocked where I work. I was wondering if there's a way to mimic Rails behavior by send ...

What is the best way to handle a JavaScript POST request in an ASP.NET WebForm?

Although it may seem like a basic question, I am a bit rusty when it comes to webforms. This is my first time using Stripe.js and I would like to utilize it alongside stripe.net for client-side processing. Below is the client code: <%@ Page Title="" La ...

What is the best way to swap out an array with a new array in Vue?

Every 10 seconds, I am querying my database for the latest fire calls. When I use app.events = data.calls, the data does not refresh. I initialize the data with the same function that is called every 10 seconds and I can see the table. How do I replace a ...

Utilizing asynchronous functions to assign a JSON dataset to a variable

Having an issue here! I've created a function to retrieve data from a local JSON file on my server. The problem is that the data is returned asynchronously, so when I try to set it to a variable for later use, it always ends up being undefined. I don& ...

What is the best way to store tests away from the source directory in Vite projects?

Executing npm init vue@latest using the specified setup https://i.stack.imgur.com/2c7XX.png results in a Vitest spec file being created in the src directory. I am curious as to why Cypress e2e tests are placed in a separate directory while Vitest unit te ...

Combining package.json commands for launching both an Express server and a Vue app

I recently developed an application using Vue.js and express.js. As of now, I find myself having to open two separate terminal windows in order to run npm run serve in one and npm start in the other. My ultimate goal is to streamline this process and have ...

The requested style from ' was denied due to its MIME type ('text/html') not being compatible with supported stylesheet MIME types, and strict MIME checking is enforced

It's strange because my style.css file in the public folder works on one page but gives me an error on another. I'm not sure why it would work on one page and not on the other. The CSS is imported in index.html so it should work on all pages of t ...

How can I ensure security measures are in place to avoid XSS attacks on user-generated HTML content?

Currently, I am in the process of developing a web application that will allow users to upload entire web pages onto my platform. My initial thought was to utilize HTML Purifier from http://htmlpurifier.org/, but I am hesitant because this tool alters the ...

Challenges encountered while working with OpenWeather API

I created a weather prediction web application using p5.js. It functions perfectly on my local server. However, I keep encountering this issue on the GitHub page: Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure ...