The reactivity of vuex state seems to be lacking

Implementing a loading spinner condition using Vuex to manage loading = true/false across multiple components.

LoadingSpinner.vue

<template>
  <fulfilling-square-spinner
    v-show="loading"
    class="loading-spinner"
    :animation-duration="4000"
    :size="50"
    color="#007bff"
  />
</template>

<script>
import { FulfillingSquareSpinner } from 'epic-spinners';
import { mapState } from 'vuex';
export default {
  components: {
    FulfillingSquareSpinner
  },
  computed: {
    ...mapState({}),
    loading: function() {
      return this.$store.state.isLoading;
    }
  },
}
</script>

<style lang="scss" scoped>
  .loading-spinner {
    z-index: 1;
    position: absolute;
    top: 315px;
    left: 0;
    right: 0;
    margin: auto;
  }
</style>

Utilizing a third-party loading spinner called Epic Spinners, which is wrapped up for consistent styling and positioning on various components.

Below is the store setup for the LoadingSpinner:

const state = {
  data() {
    return {
      isLoading: false
    }
  },
};
const getters = {};
const actions = {};
const mutations = {
  loading(state, isLoading) {
    console.log({isLoading})
    if (isLoading) {
      state.isLoading = true;
    } else {
      state.isLoading = false;
    }
  }
};
export default {
  state,
  getters,
  actions,
  mutations,
};

The goal is to toggle the spinner to true before an axios call starts and then back to false when axios finishes.

this.$store.commit('loading', true);
or 
this.$store.commit('loading', false);

The issue currently is that the spinner is not reactive and does not toggle between true or false. The computed property defined inside LoadingSpinner.vue is undefined.

Answer №1

When utilizing mapState, it is best to access the data directly instead of through $store.

computed: {
  ...mapState(['isLoading'])
  // Access `isLoading` as a property of `this`, like this.isLoading
}

Using the reactive property simplifies the process.

<template>
  <fulfilling-square-spinner
    v-show="isLoading"
    class="loading-spinner"
    :animation-duration="4000"
    :size="50"
    color="#007bff"
  />
</template>

You can also make use of mapMutations for handling mutations.

methods: {
  ...mapMutations(['loading'])
  // Mapped as this.$store.commit('loading'), and used as a property of this

  // Example usage: this.loading()
}

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

Guide on implementing Vuetify Component Slot Function

Can someone help me figure out how to implement the v-alert dismissible component with additional functionality when the close button is clicked? According to the documentation, there is a function called toggle in the close slot that allows you to "Toggle ...

Tips for handling date type input to accommodate both JSON format and date format within AngularJS

I have a RESTful service that both produces and consumes JSON objects. { firstName: "Alex", lastName: "Ross", studentGroup: { groupId: 1, groupName: "java 15-1" }, admissionDate: "2015-03-25", status: { statusId: 3, statusName: "expelled" }, term: { termI ...

Struggling to understand how to personalize a D3 generated graph

Currently, I am utilizing react-d3 instead of the Plotly react wrapper due to some bugs in the latter. My issue now lies in understanding the d3 API as I am unable to fully grasp it. I have successfully created a scatter plot similar to the one shown on ...

How do I retrieve and display all the locally stored variables in Angular 2/JavaScript and calculate the total number of keys present in the localStorage?

Currently, I'm developing a project in Angular2 that involves the storage of user-added items to a shopping cart. To accomplish this, I have opted to utilize local storage to temporarily save the items. Each category (such as shoes, clothes, etc.) is ...

The concept of an undefined object without a question mark is frowned upon

Consider the following code snippet: app-config.json { "auth": { "clientId": "acb610688b49", }, "cache": { "cacheLocation": "localStorage" }, "scopes": { "loginRequest": ["openid", "profile", "user.read"] }, "resources": { " ...

Preventing a draggable item from being dropped into a sortable container when the maximum count has been reached

Check out the following code snippet: <link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.0/jquer ...

Adjusting the height of an IFRAME on the fly

One solution to dynamically fix the height issue of Google Trend charts is by modifying the code output. An example of this can be seen in the code snippet below: <iframe width="600" height="320" src="http://www.google.com/trends/fetchComponent?hl=en-U ...

Removing a value from a JavaScript object

Looking to delete a specific value from an object with multiple values? This is how my object is structured: { 'how can i change my password?': [ 'how can I change my password?', 'how may I change my password?', ...

Is it possible to access dl, dt, or dd tags based on their roles within the testing library?

Is there a way to use the testing library to specifically target the dd tag based on its role? <dl> <dt>ID</dt> <dd>123456</dd> </dl> I attempted: screen.getByRole('term', { name: 'ID' }) as wel ...

Unable to transfer data successfully from popup to extension.js

I am currently developing a browser extension using Crossrider and I'm facing an issue with sending data from the popup to extension.js Here is my code for the popup: <!DOCTYPE html> <html> <head> <!-- This meta tag is relevant ...

Unraveling HTML elements within a string using MongoDB: A step-by-step guide

Currently, I am in the process of creating a blog from scratch as a way to enhance my skills. The posts' content is stored as a long string in MongoDB with some random HTML tags added for testing purposes. I am curious about the conventional method fo ...

Creating Vue views within Electron applications to use as plugins

Developing a reporting application in electron involves establishing a data source where users can customize views to arrange the information as required for printing or archiving in PDF format. For instance, if you have a list of student data including g ...

stop automatic resizing of windows

My CSS is written using percentages. I need to maintain the percentages intact. Is there a way to stop the layout from changing when the browser window is resized? I want the percentages to remain unaffected, even when the browser window is being resized ...

Encountered a server issue (500 Internal Server Error) when attempting to send a POST

I have been working on a social media app project using React and MongoDB. However, every time I try to register a user, I encounter a POST error in the console. I have reviewed both my client-side and server-side code, but I am still unable to successfull ...

extract data from JSON using JavaScript

I am attempting to load a php/json file which contains the following data: echo '{'; echo '"position":['; while($inhoud = mysql_fetch_array($result)) { echo '{'; echo '"lat":"'.$inhoud['lat'].'",& ...

Guide on incorporating JavaScript code within a PDF document

Looking for guidance on implementing JavaScript in PDF files I am seeking advice from those familiar with adding JavaScript actions to PDF documents, as this is a new area of exploration for me. While I have experience with JavaScript in web development, ...

An HTML attribute that evaluates to true if a condition is met

In my ng-repeat, each repeated item contains an input box where autofocus is set. This causes autofocus to be applied to all items, but in iOS, there's a bug that auto focuses on the last input box instead of the first one. To fix this issue, I need ...

Strategies for effective communication between client and server for websites containing a large volume of images

I am embarking on the creation of a comic book reading website that will host thousands of images stored on the server. Each series consists of hundreds of chapters, each containing numerous images. My goal is to efficiently display these images on my site ...

What is the process for extracting the value of a checkbox generated through JavaScript?

I recently came across a helpful post on Stack Overflow that provided sample code demonstrating how to display multiple list of checkboxes dynamically on a dropdown list. The function in the code was exactly what I needed for my webpage. However, I encount ...

Encounter issues with v-for functionality when using Internet Explorer 11

I am facing an issue with the rendering of a table in a simple Vue instance. The document displays correctly on Firefox and Chrome, however, I encounter an error in IE11: [Vue warn]: Error when rendering root instance. I assumed that Vue is compatible ...