Storing data retrieved with Axios in Vuex state through a Vuex action

According to the Axios documentation, I am trying to simultaneously retrieve data from two sources on my backend (block.json and type.json) within the actions of my Vuex store. I have declared myBlocks and myTypes as data in my Vuex State. Although I am able to fetch the data successfully, I am facing an issue with assigning the fetched data to the variables in the Vuex state. When I try to reference the state using console.log(state.sample), I get undefined instead of foo. However, when I use console.log(state), it outputs the following result shown in the image linked below. Any suggestions on how to resolve this would be highly appreciated. https://i.sstatic.net/5iSuY.png

state: {
  sample: 'foo',
  myBlocks: [],
  myTypes: []

},


actions: {
  fetchElementColors: function(state) {
      function getElementBlockColors() { return axios.get('/element-data/block.json'); }
      function getCategoryDataColors() { return axios.get('/element-data/type.json'); }

      axios.all([getElementBlockColors(), getCategoryDataColors()])
        .then(axios.spread(function(blockData, categoryData) {
          console.log(state);
          console.log(state.sample);
          state.myBlocks= blockData.data;
          state.myTypes= categoryData.data;
        }));
    }

}

Answer №1

When working with your actions, make sure to access the context object instead of the state.

To achieve this, modify your code as shown below:

actions: {
  fetchElementColors: function(context) {
      function getElementBlockColors() { return axios.get('/element-data/block.json'); }
      function getCategoryDataColors() { return axios.get('/element-data/type.json'); }

      axios.all([getElementBlockColors(), getCategoryDataColors()])
        .then(axios.spread(function(blockData, categoryData) {
          console.log(context.state);
          console.log(context.state.sample);
          context.state.myBlocks= blockData.data;
          context.state.myTypes= categoryData.data;
        }));
    }

}

For more information, visit: https://vuex.vuejs.org/guide/actions.html

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

Spotting the Visible Element; Detecting the Element in

Currently, my webpage has a fixed header and I am facing the challenge of dynamically changing the styling of the li elements within the navigation based on the user's scrolling position. To achieve this, I believe the most effective approach would b ...

Having trouble with properly writing to multidimensional arrays?

The issue I am encountering is clearly depicted in the simplified code snippet below. During the execution of the TestArrays function, the goal is to write a single item to each location in the multidimensional array. However, upon examining the layers in ...

Steps to release a react application as an npm package

Hey there! I have a set of JavaScript files named auth.js, cookies.js, hooks.js, product.js, and index.js. My plan is to package them using npm for publishing. In my index.js file, I am exporting all the other files with the syntax: export * from './ ...

Utilizing CSS-in-JS to eliminate arrow buttons from a TextField

I'm currently developing a webpage using React and Material-UI. One of the components I have is a TextField element, and I need to remove the arrow buttons that typically appear on number input fields. If I were utilizing CSS, I could easily achieve t ...

How can I pass functions from the Parent Context Provider to the Child Context Provider and define them in React?

Recently delving into the world of React, I've encountered a challenge with using the Context API alongside React Functional Components Specifically, I'm faced with a situation where I need to differentiate authentication providers based on th ...

Utilize Javascript to refine JSON data strings

Currently, I am tackling a small project and facing a minor JS issue. The JSON string that I have looks like this: var jsObj = { "templates": { "form0": { "ID": "MyAlertNew", "isVisible": "true", ...

Tips for preserving axois GET response as a JSON object or in its original form upon arrival

export class LoadProfile extends Component { state = { data: '' } componentDidMount() { axios({ url: 'http://localhost:8080/profile/all', method: 'GET', responseType: 'json', ...

Avoid updating the input from ng-model while it is being edited

There are times when my model.field can be altered by both user input into an input field and by other functions running in the background. However, I want to handle situations where changes made by the user take precedence over modifications made by those ...

Events are not being received by the Discord.js client

My client is not receiving any interactions (slash commands) even though it should be able to handle them require("dotenv").config(); const { Client } = require("discord.js"); //disc = require("discord.js"); const axios = re ...

Using Vue as the host platform and React as the remote component in a microfrontend setup

I'm in the process of developing a microfrontend application that utilizes Vue for the host and React for the remote component. For this project, I am utilizing Vite along with Module Federation (vite-plugin-federation). Host Application App.vue: & ...

Error 107 occurred while attempting to parse JSON data using the AJAX technique with the REST API

I've encountered an issue while attempting to utilize the Parse REST API for sending push notifications. Every time I make an AJAX call, I receive an invalid JSON error in the response and a status code of 400. Below is my request: $.ajax({ url: & ...

Error: The "use client" component does not recognize either window or localStorage

I'm currently working on creating a wrapper function that can be used in every dashboard component. "use client"; const UserWrapper = ({ children }) => { const user = JSON.parse(window.localStorage.getItem("ysg_u")); retur ...

ngCropper - dynamically adjust aspect ratio with a click of a button

I am currently working with ngCropper and I need to be able to dynamically change the aspect ratio on button click, similar to how it is done in JavaScript cropper () Below is the default option that has been set up: vm.options = { maximize: true, ...

Tips for verifying an alphanumeric email address

I need to create an email validation script that allows only alphanumeric characters. <script type = "text/javascript"> function checkField(email) { if (/[^0-9a-bA-B\s]/gi.test(email.value)) { alert ("Only alphanumeric characters and spaces are ...

display a different selection option depending on the previously chosen item

I'm working on displaying additional options in a select box when the user makes a selection from the main select box. I've set display:none for the select boxes, which will only appear when the user chooses an option from the main select box. C ...

An incorrect object was removed from the array

Having an issue where the wrong item is getting deleted from an array in my component's state. Here is a simplified version of my parent Component: export default class BankList extends Component { state = { banks: [new Bank("Name1"), new ...

When the request's credentials mode is set to 'include', the 'Access-Control-Allow-Origin' header in the response should not be using the wildcard '*'

I am encountering an issue with my socket.io server as I am unable to connect to it from my local HTML file on my Mac. Error: Failed to load : The 'Access-Control-Allow-Origin' header in the response is causing a problem due to the wildcard ...

The `Ext.create` function yields a constructor rather than an object as

Ext.application({ name: 'example', launch: function() { var panel = Ext.create('Ext.panel.Panel', { id:'myPanel', renderTo: Ext.getBody(), width: 400, ...

Struggling with populating a dropdown in MVC with JSON data fetched from an API using jQuery/JavaScript

I am struggling to bind the JSON data retrieved from an API to a dropdown list. I am having trouble extracting the values for id and name from the JSON format shown below: { "categories": [ { "categories": { "id": 1, ...

JavaScript maintaining records and connections between multiple asynchronous events

I am working on an Angular 10 project where users can compress and upload images to Google Cloud Storage. The compression and uploading functionalities are functional, but I'm facing challenges with managing the asynchronous process of handling multip ...