The V-snackbar fails to show up after I make changes to the Vuex state

I am facing an issue with my <v-snackbar> component not showing when I update the Vuex state.

The setup is straightforward: I have a snackbar in Snackbar.js, which listens for changes in the state.

This Snackbar.js is then imported as a child component in App.vue to make it global.

Subsequently, Test.vue contains a simple button. Upon clicking the button, I expect the State to be updated and the snackbar to render, but it fails to do so.

Upon inspecting the Snackbar component using Chrome Vue Devtools, I noticed that the data does reach the store, but somehow doesn't update the reactive props in Test.vue https://i.sstatic.net/6xzPG.png

Below are the relevant code snippets:


Snackbar.vue

<template>
  <v-snackbar v-model="show" :top="top" multi-line rounded="pill">
    {{ text }}
    <v-btn text @click.native="show = false">
      <v-icon>close</v-icon>
    </v-btn>
  </v-snackbar>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data () {
    return {
      show: false,
      text: '',
      top: true
    }
  },
  computed: {
    ...mapState(['snackbar'])
  },
  created: () => {
    this.unwatch = this.$store.watch(
      // watch snackbar state
      (state, getters) => getters.snackbar,
      () => {
        const text = this.$store.state.snackbar.text
        if (text) {
          this.show = true
          this.text = text
        } 
      }
    )
  },
  beforeDestroy () {
    this.unwatch()
  }
}
</script>

App.vue

<template>
  <v-app>
    <v-main>
      <!-- try to set a global snackbar -->
      <Snackbar/>
      <router-view/>
    </v-main>
  </v-app>
</template>

<script>
import Snackbar from '@/components/Snackbar'

export default {
  name: 'App',
  components: {
    Snackbar
  }
}
</script>


Test.vue

<template>
    <v-btn @click="passData">Show snackbar</v-btn>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  name: 'Test',
  data: () => ({
    //
  }),
  computed: {},
  methods: {
    ...mapActions([
      'setSnackbar'
    ]),
    passData () {
      this.setSnackbar({
        text: 'Simple message',
        isActive: true
      })
    }
  }
}
</script>

Store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    snackbar: {
      isActive: false,
      text: ''
    }
  },
  getters: {
    snackbar (state) {
      return state.snackbar
    }
  },
  mutations: {
    populateSnackbar (state, payload) {
      state.snackbar.isActive = payload.isActive
      state.snackbar.text = payload.text
    }
  },
  actions: {
    setSnackbar (context, payload) {
      context.commit('populateSnackbar', payload)
    }
  }
})

Answer №1

The code snippet above will display a snackbar upon its initial creation, but subsequent attempts to trigger it may not work as expected due to Vue reactivity.

In this scenario, the state is updated, but the data properties within the snackbar component do not reflect these changes.

To address this issue, consider replacing the snackbar component with the following implementation:

<template>
  <v-snackbar v-model="snackbar.show" :top="top" multi-line rounded="pill">
    {{ snackbar.text }}
    <v-btn text @click.native="$store.dispatch('setSnackbar', {text: '', isActive: false})">
      <v-icon>close</v-icon>
    </v-btn>
  </v-snackbar>
</template>

<script>
import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState(['snackbar'])
  },

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

Filter jQuery search results for classes with identical names

I am new to using jQuery, so please excuse my lack of experience. My current challenge involves 'getting a reference to an object wrapped in a class', but there are multiple classes with the same name. How can I specifically target and retrieve t ...

The 'Required' attribute in HTML is malfunctioning

The 'required' attribute is not functioning properly when I try to submit the form. I've searched online for a solution, but none of them have resolved my problem. Take a look at the code snippet below - I've used the required attribute ...

Acquiring an icon of a program using its handle

I am looking for a way to extract a program's icon from its handle, which I acquired using User32.dll with EnumWindow/FindWindow. While I am aware of ExtractAssociatedIcon, it seems to work from a file instead of a handle. My question is how can I con ...

Transferring information between pages in PHP

Currently, I am exploring the most effective way to pass data between two pages (Page A to Page B) using PHP for a specific scenario: Page A: This page displays a gallery of images with titles. The PHP file makes a database call to an images table, which ...

What is the process for authenticating and sending a click conversion to Google Ads using a service account and the REST API with TypeScript?

I have attempted to authenticate using this documentation and to send conversions via REST API using this REST endpoint due to the absence of a Typescript/Javascript Client Library. However, I am encountering authentication issues. Once resolved, I aim to ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

ajax-jquery request declined

I have a jquery-ajax function that is being called multiple times with different IP addresses each time. This function makes a call to an action in the mvc4 controller responsible for executing a ping and returning the results. After analyzing the request ...

Is a Singleton really necessary for my situation?

I am currently developing a Firefox extension that requires keeping multiple windows synchronized with the same information. The toolbar in each window queries a remote server periodically, but since Firefox windows are isolated environments with their own ...

A guide on utilizing webpack devServer proxy within a create react app

Currently, I am in the process of developing a new application with create-react-app and I am looking to incorporate some proxies into my code. In the past, I utilized webpack's devServer for this purpose. module.exports = { ... devServer: { ...

successive ajax requests

I am facing a challenge where I need to execute two separate ajax calls sequentially. The second call relies on the result of the first call for its data. Despite my efforts, I haven't been able to achieve the desired outcome. Here's what I have ...

Google Maps integrated AWS server

While utilizing an AWS server for my application, I have encountered a difficulty with Google Maps. When running my application using localhost, Google Maps functions perfectly fine. However, when attempting to run the application using an IP address, it f ...

AngularJS modifying shared factory object across controllers

Is it possible to update the scope variable pointing to a factory object after the factory object has been updated? In cases where there are 2 angular controllers sharing a factory object, a change made to the factory object by one controller does not re ...

Headers cannot be set once they have already been sent in an express js application

After reviewing various responses to this query, I am baffled as to why this error keeps appearing despite having res.send() in multiple paths. In my code (expressjs 4.13), it looks something like this: var user ={ username: "some", password: "a" ...

What is the best way to showcase the proper layout of my article, created using a WYSIWYG editor, with the help of Vue.js and Laravel

Can anyone provide guidance on how to display a customized article from a WYSIWYG editor using Vue.js? In Laravel, I am accustomed to using {!! $article->content !!} to show the full content. How can I achieve the same result in Vue.js using {{article ...

Utilize the Spotify API to discover tracks by including the album title and artist's name in the search

Currently working on a project that involves searching for a music track on Spotify. The idea is to input the track name in the text area and generate a list of matching Track IDs along with Artist Names, Album Names, and Artwork. I have made some progress ...

Encountering a call stack size error when utilizing Vue-Resource within a Vuex store

I'm struggling to integrate an array from my api into a component using Vuex. The code I had when accessing the api directly from the component worked fine: data () { return { catalog:[], } }, created() { this.$http.get('https://example.net ...

I continue to encounter the error "Unexpected token b in JSON at position 0" when attempting to parse JSON data

Having some trouble with my code that generates an HTML page. The signup function allows users to register and create a password, while the checkpassword function is supposed to verify if the correct password is entered for the given username. I seem to be ...

Utilizing Vue and Vuex to manage state

Hello everyone, good morning! I've been facing challenges for the past few days while working on an app for gaining some experience. I've made significant progress, but I'm currently struggling with the state management aspect, particularly ...

What is the best way to obtain the chosen value or index from a Vue select element?

On the surface, this question seems straightforward, but there are some complexities to consider. The scenario involves: <select id="lstMash" @change="onChange()"><option value="valid">Valid</option><option value="warning">Warning& ...

Fundamental JavaScript feature experiencing functionality issues

Greetings, this is my debut in this space and I am encountering some challenges as a beginner in the world of coding. It seems that passing arguments to parameters is where I'm hitting a roadblock, or perhaps there's a simple detail that I'm ...