Issue with Vuex. While this.$store.dispatch(...) is functional, ...mapAction is not working as expected

I am encountering an issue with dispatching Actions from vuex. It's puzzling to me that ...mapActions is not initiating a request to Jsonplaceholder. However, using this.$store.dispatch successfully retrieves all 10 users without any issues. Below are the scripts for two files: home.vue page and store.js:

HOME:

<script>
  import { mapGetters, mapActions } from "vuex";
  export default {
    name: "Home",
    created() {
      // this.$store.dispatch('fetchUsers')
      console.log(this.$store);
    },
    computed: {
      ...mapGetters(["getUsers"])
    },
    methods: {
      ...mapActions(["fetchUsers"]),
      increment() {
        this.$store.commit("increment");
        console.log(this.$store.state.count);
      }
    }
  };
</script>

STORE:

const store = new Vuex.Store({
  state: {
    count: 0,
    users: []
  },
  getters: {
    getUsers(state) {
      return state.users;
    }
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    setUsers(state, users) {
      console.log(state, users);
      state.users = users;
    }
  },
  actions: {
    fetchUsers({ commit }) {
      return new Promise(resolve => {
        fetch("https://jsonplaceholder.typicode.com/users")
          .then(response => {
            return response.json();
          })
          .then(result => {
            console.log(result);
            commit("setUsers", result);
            return resolve;
          })
          .catch(error => {
            console.log(error.statusText);
          });
      });
    },
    incrementUsers({ commit }) {
      commit("fetchUsers");
    }
  }
});

Answer №1

When utilizing mapGetters and mapActions in your code:

import {mapGetters, mapActions} from 'vuex'

You can simplify the process by doing this instead:

created() {
  this.fetchUsers()
  console.log(this.getUsers)
},
computed: {
  ...mapGetters(['getUsers'])
},
methods: {
  ...mapActions(['fetchUsers']),
}

If you prefer name-spacing, you can refer to this solution:

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

Fluid zooming and panning capabilities when using a logarithmic axis

I'm having trouble with enabling zoom and panning on a Flot plot with a logarithmic x-axis. Every time I attempt to zoom or pan, all the points on the plot disappear and I need to refresh the page. Below is the link to the jsfiddle where I have the f ...

The function "useLocation" can only be utilized within the scope of a <RouterProvider> in react-router. An Uncaught Error is thrown when trying to use useLocation() outside of a <Router>

When attempting to utilize the useLocation hook in my component, I encountered an error: import React, { useEffect } from 'react'; import { useLocation } from 'react-router-dom'; import { connect } from 'react-redux'; import { ...

The issue of Select2 with AJAX getting hidden behind a modal is causing

I'm currently facing an issue with Select2 within a modal. The problem can be seen here: https://gyazo.com/a1f4eb91c7d6d8a3730bfb3ca610cde6 The search results are displaying behind the modal. How can I resolve this issue? I have gone through similar ...

Troubleshooting AJAX issues in Firefox with window.location.assign function

Here is my AJAX POST request that sends serialized form data to the server: // Handle form submission. $('#evaluationform').on('submit', function(e){ e.preventDefault(); ajaxObject = { url: $("#evaluationform").attr("a ...

The switch switches on yet another switch

Greetings everyone, Currently, I am in the midst of my exam project and creating a mobile menu. The functionality is there, but unfortunately, when closing the menu, it also triggers the search toggle which displays an unwanted div, becoming quite botherso ...

I am attempting to establish a connection with the Converge Pro 2 system from Clearone using NodeJS node-telnet-client, but unfortunately, my efforts to connect have been unsuccessful

My connection settings are as follows: { host: '192.168.10.28', port: 23, shellPrompt: '=>', timeout: 1500, loginPrompt: '/Username[: ]*$/i', passwordPrompt: '/Password: /i', username: 'clearone ...

Retrieve information from the index resource using AJAX

I feel like I might be overcomplicating things, but basically, I'm trying to retrieve all the data from an index resource and have it load when a button is clicked using AJAX. I've been using a serializer to tidy up the JSON. Both "/categories" ...

Tips for sending data to Jade templates:1. Use the `locals`

Review the code below user.js exports.index = function (req, res){ res.render('user', { id: req.params.id }); }; user.jade body - var x = #{id} div.container div.headpic if (x < 10) ...

Executing a javascript function numerous times

Here are a few examples: <div class="statement">text goes here</div> <div class="response"><input type="text" id="amount1" style="border: 0; color: #f6931f; font-weight: bold;" /></div> <div id="sli ...

Regular expressions won't produce a match if the string is empty

At present, I am employing the regular expression /^[a-zA-Z.+-. ']+$/ to ascertain the validity of incoming strings. If the incoming string is devoid of content or solely comprises whitespace characters, my objective is for the code to generate an er ...

Transform the file format from .casa-model to .obj

Looking for a way to convert a file with the extension .casa-model to .obj format. Is there any solution available? Find the model here. ...

How can I trigger a masterpage function from a contentpage in asp.net?

I am trying to call a function on the masterpage from a content page in the codebehind. Here is my attempt: ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert__", string.Format("setStatusBarMessage('{0}',{1});", barMessage, ty ...

Tips for generating a JSON string with nested structure

Can someone assist me in generating a JSON based on the HTML elements provided below? { "AppName": "ERP", "ModuleDesc": [ { "Name": "Payroll", "AcCESSRIGHTS": [ { "Create": "Y", "Retrive": "Y", "U ...

Issue with setting state in useEffect causing an infinite loop due to either linter warning or user error

In its current state, my component appears as follows: const { listOfStuff = [{name:"john"},{name:"smith"}] } = props const [peopleNames, setPeopleNames] = useState([]) useEffect(() => { listOfStuff.forEach(userName => { setPeopleNames(people ...

Generate several invoices with just a single click using TypeScript

I'm interested in efficiently printing multiple custom HTML invoices with just one click, similar to this example: https://i.sstatic.net/hAQgv.png Although I attempted to achieve this functionality using the following method, it appears to be incorr ...

Is there a way to retrieve the headers from an HTTP response in JavaScript that wasn't initiated by an AJAX request?

I have a login page setup to send an HTTP post request to the server, which then redirects me to another page on the server in the response message. On this new page, I need to access the location header to obtain a specific value for future server tasks. ...

Unraveling TypeScript code expressions

I am seeking clarification on the meaning and practical application of this particular expression. ((identifier:string) => myFunction(identifier))('Hi') myFunction const myFunction = (str:string) => { console.log(str) } The output displ ...

Is it possible to alter the css twice through the action of clicking on two individual buttons

One feature I have in my interface allows users to click on the edit button to bring up borders and change the background color of other divs. Once the edit button is pressed, it is replaced by cancel and save buttons. The goal is for the borders and backg ...

How can I incorporate a CDN link into the newly updated Next.js App Router?

Exploring next.js has been quite an adventure for me, and I'm impressed with its capabilities. However, being a beginner, I have encountered some challenges. One issue I am currently facing is the difficulty in using Google icons without a CDN link in ...

A single block in Javascript uses the ternary operator (?:) to make changes to an object and return

Can you modify a dictionary inside the ?: statement and then return the updated dictionary in the same block? For example, something like this: a > b ? <dict['c'] = 'I'm changed', return dict> : <some other code>; I ...