Guide to Updating Store State with API Data

My goal is to update my component state with data retrieved from an API using a getter in the store.

Within the mounted() lifecycle hook, I call the getProducts() getter which is defined as:

export const getters = {
  async getProducts() {
    axios.get('/api/products')
      .then(res => {
        var data = res.data
        commit('setProducts', data)
      })
      .catch(err => console.log(err));
  }
}

The getProducts() getter attempts to execute a mutation named setProducts(), which is defined as follows:

export const mutations = {
  setProducts(state, data) {
    state.products = data
  }
}

However, upon running this code, I encounter the error ReferenceError: commit is not defined in the console.

The issue seems to be related to triggering the mutation, and despite extensive research over two days, I have been unable to find a solution.

I attempted replacing commit('setProducts', data) with: this.setProducts(data) setProducts(data)

Unfortunately, all of these attempts resulted in the error "TypeError: Cannot read properties of undefined (reading 'setProducts')".

Answer №1

In a Vue component, if your function getProduct is defined, you can access the store by using

this.$store.commit('setProducts', data)

If the function is outside of a Vue component, import the store from an external JavaScript file:

import store from './fileWhereIsYourStore.js'

store.commit('setProducts', data)

If your getters export contains the definition of your store's getters, importing the store first is a solution, but it's not recommended to make commits in getters. Find a better approach.

EDIT: To address a comment, here's an example implementation:

// Store module 
export default {
  state: {
    products: []
  },

  mutations: {
    SET_PRODUCTS(state, data) {
      state.products = data
    }
  },

  actions: {
    async fetchProducts(store) {
      await axios.get('/api/products')
        .then(res => {
          var data = res.data
          store.commit('SET_PRODUCTS', data)
        })
        .catch(err => console.log(err));
    }
  }
}

Now, in each component, you can fetch and populate the store like so:

// Random Vue Component
<template>
</template>

<script>
export default {
 async mounted() {
   await this.$store.dispatch('fetchProducts')

   // Access products like this
   console.log(this.$store.state.products)
 }
}
</script>

This code should work properly, although I haven't tested it.

Answer №2

Actions are the only ones that have commit in their context, as shown here.
Getters do not have access to commit.

Alternatively, you can utilize mapActions (or

import { mapActions } from 'vuex'
) instead of using this.$store.dispatch (it's just a matter of preference, no real difference in the end).

Following Julien's suggestion to refactor your code and use actions is a recommended approach when working with Vuex.

Getters are typically used for manipulating state with specific structures, such as sorting alphabetically. For general state access, consider using the regular state or the mapState helper.

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

Trapped in a Continuous Observing Loop with MdSnackBar in Angular Material within Angular 2

Whenever my login attempt fails, I want to display a snackbar with the message 'error connecting'. After dismissing the snackbar, I would like the login to be retried after 10 seconds. However, I'm facing an issue where my observable is runn ...

Issues arise when attempting to make a SOAP request in NodeJS, as opposed to PHP where it functions seamlessly

As I work on integrating a SOAP-API to access data, I encounter an error when trying to implement it in my ExpressJS-Service using NodeJS. The API documentation provides examples in PHP, which is not my preferred language. My PHP implementation works flawl ...

Unique style pattern for parent links with both nested and non-nested elements

I am in the process of designing a website and I have a specific vision for how I want my links to appear, but I am unsure of how to achieve it. Here is the desired outcome: a red link a green link a red link a green link … Below is the HTM ...

Switch the following line utilizing a regular expression

Currently, I am facing a challenge with a large file that needs translation for the WordPress LocoTranslate plugin. Specifically, I need to translate the content within the msgstr quotes based on the content in the msgid quotes. An example of this is: #: . ...

I'm experiencing some issues with my scene in ThreeJS - the HDR background isn't displaying, and my cube

<style> body { margin: 0; } </style> <script async src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afcadc82c2c0cbdac3ca82dcc7c6c2dcef9e8199819c">[email protected]&l ...

Error: Authentication Error - Headers have already been sent to the client and cannot be modified

I am currently working on handling authentication errors for my website. However, when I submit incorrect data, I encounter the following error: node:internal/errors:478 ErrorCaptureStackTrace(err); ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers aft ...

What is the best way to automatically build a Single Page Application when deploying to Heroku?

Currently, I am in the process of learning how to deploy my Vue app to Heroku. After deploying my code to Heroku, I am facing a challenge when trying to automatically build my code to the dist/<code> folder. Despite attempting to configure the packag ...

Having trouble rendering a model using OBJLoader in React Three Fiber

I'm having issues with rendering an .obj file in my React project using the OBJLoader and useLoader() hook from React Three Fiber. Despite ensuring that my file path is correct and wrapping the Model component in Suspense tags, I am still encountering ...

Implement Material-UI's built-in validation for form submission

I'm in the process of setting up a form with validation: import React from 'react'; import { useForm } from "react-hook-form"; import axios, {AxiosResponse} from "axios"; import {Box, Button, Container, Grid, Typography} ...

Error message: "Reactjs - TypeError: The property 'map' cannot be read as it is undefined in the table"

I have encountered an issue while using the material-ui table. I am able to map the items and display them successfully, but when trying to map the orders.items in the table, I get the following error: TypeError: Cannot read property 'map' of u ...

Encountering difficulties when trying to display a nested object with two levels of depth using

I am currently developing an application where I need to display a nested object with two levels using the map method. The data structure is as follows: const categories = [ { catName: "Education", subCategory: [ { subCatName: "Col ...

NodeJS instructs open(html) to execute first before any other code is executed

I am evaluating whether nodeJS is a suitable solution for a project I am working on during my internship. To summarize: I need the basicNode.js file to wait until the open('./basic.html') command has completely opened the browser and loaded its c ...

`Storing modified PDF containing interactive form elements using integrated Chrome viewer and transferring it to a remote server`

Our current setup utilizes the default embedded Chrome PDF viewer to showcase a PDF document with interactive form fields, enabling users to conveniently fill out the form. Once completed, they can click on the download button to save the form with or with ...

Parsing JavaScript JSON using PHP's json_decode method is a powerful feature

In my current scenario, I am encountering situations where I extract a JSON string from an HTML page and pass it to the `json_decode` function. Sometimes it succeeds, but other times `json_decode` returns null. How can I enhance my solution to ensure that ...

Having trouble updating a MongoDB array through a RESTful API PUT request

I'm brand new to the MEAN stack and recently completed a tutorial. I've been working on enhancing a simple application that utilizes a RESTful API to update a MongoDB. Currently, I'm using a PUT statement to modify specific parts of my colle ...

react-intersection-observer is specifically designed to function with the final elements

I am currently working on implementing the Lazy Loading feature using react-intersection-observer. The main objective is to load images in the boxes only when they appear within the viewport. At the moment, as I scroll down to the last elements, all the i ...

Formatting dates for the bootstrap datepicker

Hi there! I am currently using a bootstrap datepicker and I am attempting to retrieve the value from the datepicker text box in the format of date-month-year for my controller. However, at the moment, I am only able to obtain values in the format Tue Oct 0 ...

Is there a way to determine if two distinct selectors are targeting the same element on a webpage?

Consider the webpage shown below <div id="something"> <div id="selected"> </div> </div> Within playwright, I am using two selectors as follows.. selectorA = "#something >> div >> nth=1&q ...

Alert: A notification appears when executing Karma on grunt stating that 'The API interface has been updated'

While executing karma from a grunt task, I encountered the following warning: Running "karma:unit" (karma) task Warning: The api interface has changed. Please use server = new Server(config, [done]) server.start() instead. Use --force to continue. A ...

Create a custom hook that encapsulates the useQuery function from tRPC and provides accurate TypeScript typings

I have integrated tRPC into a project that already has API calls, and I am looking to create a separate wrapper for the useQuery function. However, I am facing challenges in getting the TypeScript types right for this customization. My Objective This is w ...