What strategies are effective for handling state reactively in Vuex?

Currently, I am facing an issue with my vuex store. I have implemented two different actions in my store, one being reactive and the other not. However, I specifically need the loadSlidesEach() action to be reactive so that the data gets updated accordingly. Despite my efforts, I am unable to pinpoint the mistake.

Below is a snippet of my store:

const store = new Vuex.Store({

  state: {
    loadedSlides: []
  },

  mutations: {
    setSlides(state, slides) {
      state.loadedSlides = slides
    },
    setSlidesPush(state, slide) {
      state.loadedSlides.push(slide)
    }
  },

  getters: {
    loadedSlides(state) {
      return state.loadedSlides
    }
  },

  actions: {
    loadSlides({ commit, getters, state }) {
      firebase.database().ref('/slides/').on('value', snapshot => {
        const slidesArray = []
        const obj = snapshot.val()
        for (const key in obj) {
          slidesArray.push({ ...obj[key], id: key })
        }
        commit('setSlides', slidesArray)
      })
    },
    loadSlidesEach({ commit, getters, state }, id) {
      firebase.database().ref('/slides/' + id).on('value', snapshot => {
        const slide = snapshot.val()
        commit('setSlidesPush', { ...slide })
      })
    }
  }
})

Component 1: Array from slides() reacts as expected

export default {
  computed: {
    slides() {
      return this.$store.getters.loadedSlides
    }
  },
  created() {
    this.$store.dispatch('loadSlides')
  }
}

Component 2: Array from slides() is not reactive

export default {
  computed: {
    slides() {
      return this.$store.getters.loadedSlides
    }
  },
  created() {
    const slides = ['1','2','3']
    for (let i = 0; i < slides.length; i++) {
      this.$store.dispatch('loadSlidesEach', slides[i])
    }
  }
}

I suspect that the issue might lie within the initial state or the mutation using push(). Any advice or suggestions?

Update: Upon further investigation, I noticed that the difference between the two actions lies in the mutations. What would be the best approach to setting the state in vuex? Calling the action loadSlidesEach() in a loop seems to confuse the store. Thoughts?

Answer №1

Avoid combining await and then. Choose either one:

loadSlidesEach: async({ commit, getters }, id) => {
  const data = await firebase.database().ref('/slides/' + id).once('value')
  const slide = data.val()
  commit('setSlidesPush', { ...slide })
}

Answer №2

Have you attempted to utilize mapState from the Vuex library?

import {mapState} from 'vuex'

export default {
  computed: {
     ...mapState(['loadedSlides '])
  }
}

You can now access the loadedSlides variable in your component.

Answer №3

I finally figured out the solution to my issue.

Here is the revised mutation code:

setSlidesUpdate(state, addedSlide) {
  const slideIndex = state.allSlides.findIndex(slide => slide.id === addedSlide.id)
  if (slideIndex !== -1) {
    Vue.set(state.allSlides, slideIndex, addedSlide)
  } else {
    state.allSlides.push(addedSlide)
  }
}

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

Which is more advantageous: returning a value or returning a local variable?

While the title may not be the best descriptor in this situation, I am unsure of how to phrase it any better. Both of these functions perform the same task: function A(a, b) { return a * b; } function B(a, b) { var c = a * b; return c; ...

How to flip the value in v-model using VueJS

Below is the code snippet that I am working with: <input v-model="comb.inactive" type="checkbox" @click="setInactive(comb.id_base_product_combination)" > I am looking to apply the opposite value of comb.inactive to the v-model. Here are m ...

I am searching for a way to apply a conditional class to the chosen element in react, as the toggle method does not

I'm working on customizing a dropdown menu and I want to add a functionality where if a parent li menu has an arrow class before the ul element, then clicking on that parent li menu will add a class called showMenu only to that specific sub-menu. Her ...

"Angular File Upload Made Easy with Drag-and-Drop Functionality and Cleverly Positioned

Encountering an issue with Angular File upload in conjunction with relatively positioned elements. The drop target is set to 100% width and height, absolutely positioned. While dragging a file over any non-relatively positioned element, the overlay functio ...

Can the state and city be filled in automatically when the zip code is entered?

I have a form where users can enter their zip code, and based on that input, the corresponding city and state will automatically populate. These three fields are positioned next to each other within the same form. Here is an example of my form: $(' ...

Tips for generating a <div> element with multiple children using a loop

section, I have configured a div element with a class named div class = "postWindow". When it comes to the HTML code, here is an example: <div class = "postWindow"> <div class = "userName">Initial Name</div> <div class = "p ...

What steps can I take to make the replaceData function function properly?

Struggling to implement replaceData, setData, or updateData functions in my project. I am using bootstrap vue along with tabulator tables. The API is functioning correctly. Tabulator works smoothly unless the API URL depends on the modal select option; how ...

Refreshing a webpage to accurately display changes made in a CRUD application without the need for a hard reset

My to-do app is almost fully functional - I can create items, mark them as completed, and delete them using a delete button. However, there's one issue: when I delete an item, the page doesn't update in real-time. I have to manually refresh the p ...

The attempt to update several partial views using Jquery, MVC, and Json is currently malfunctioning

I am facing issues with updating multiple partial views using jQuery, MVC, and JSON. The partial views on my page are not getting updated. Below is the code for my view: Here is the code for my controller: public class GetStudentsController : Controlle ...

Adjust the node's location in Cytoscape.js

I recently switched from using Cola to fCose in Cytoscape.js for graphing multiple graphs with no connections. With Cola, I was able to manually set node positions by tweaking the layout options. However, with fCose, despite adjusting variables like quali ...

Switch the dropdown menu to a button if it consists of only one option

I have been using a database within the Moodle Learning Management System that generates a bootstrap table. Here is an example of what it looks like: https://i.sstatic.net/UJc4M.png The last row in the table contains a dropdown menu. When viewing your ow ...

Understanding the Impact of npm Dependencies on AAB (Android App Bundle) Release Size in React Native

Switching over to React-Native and Node.js from a Python background has left me confused about how dependencies are managed in React-Native (which I assume is similar to node.js). Query When creating a React Native AAB, are all Node Modules declared in th ...

The value sent from the ajax call did not reach the PHP file as expected

Here's the code I'm working with: HTML and Javascript: function getValues(){ var filter; $.ajax({ type: "POST", url: "myphpfile.PHP?action=sek", data: "id=1", async: false, suc ...

Is there a way to execute "npm run dev" within cPanel while I am currently working on a Laravel project?

Currently, I am working on a Laravel project and require to execute the following command in Cpanel terminal: npm run dev https://i.sstatic.net/bzxNj.png ...

Tips on organizing and designing buttons within a canvas

let canvas = document.getElementById("canvas"); let context = canvas.getContext("2d"); // for canvas size var window_width = window.innerWidth; var window_height = window.innerHeight; canvas.style.background="yellow" canvas.wid ...

simulating the use of `usePrompt` in react-router-dom version 6

Prompt.js import { unstable_usePrompt as usePrompt } from 'react-router-dom'; // eslint-disable-next-line react/prop-types export default function CustomPrompt({ when, message }) { usePrompt({ when, message }); return null; } CustomPrompt.t ...

Is it possible to extract external JSON data using JQuery's $.getJSON function?

I am trying to retrieve a quote from the iheartquotes website and display it within a div when my webpage loads. However, for some reason, the code I have written is not working as expected. <script type="text/javascript"> $(document).ready( ...

Using AngularJS variables within JavaScript code

This is my introduction to using AngularJS. The code snippet below displays the desired output: <a href="http://www.example.com/xyz/{{life.animal}}/" target="_blank">Hello </a> Upon clicking, it redirects to: http://www.example.com/xyz/c ...

Pass the value from JavaScript to PHP

I am looking to insert a JavaScript value into PHP: var temp = $('#field_id').val().charAt(0); The 'temp' variable returns values ranging from 1 to 4. var value = "<?php echo $variable[temp]['id']; ?>"; How can I re ...

Looking for a way to store data in local storage so it remains even after the page is reloaded? I tried adding a local storage function, but it doesn't appear to be

I am currently working on a project involving a work day scheduler and I am facing challenges in saving data within the schedule events, like at 8am, and making sure it persists on reload. The colored time block element that changes as hours pass in the da ...