Unable to retrieve Vue resource within Vuex action

Hello everyone, I'm currently facing an issue while trying to make a request within my action on the Vuex side, and I keep getting this error:

Cannot read property '$http' of undefined

I have configured my vue-resource in the following manner inside my main.js file:

import Vue from 'vue'
import VueResource from 'vue-resource'
import VueRouter from 'vue-router'
import App from './App.vue'
import {routes} from './routes';
import {store} from './store/store';
import VModal from 'vue-js-modal'

Vue.use(VModal)
Vue.use(VueResource);
Vue.use(VueRouter);

const router = new VueRouter({
  routes
});

new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App)
})

Then, within the store:

addStyle(state,newStyleObj) {
    console.log(newStyleObj);
    var vm = this;
    this.$http.post('http://localhost:16339/api/Styles/PostStyle/', newStyleObj)
        .then(response => {
            state.tableStyles = response.body;
            console.log(state.tableStyles)
            console.log(response.body)
        }, error => {
            console.log(error);
        });
}

Could anyone provide assistance with this issue?

Answer №1

import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'

const customAxios = axios.create({
    baseURL: '',
    withCredentials: true,
})

Vue.prototype.$customAxios = customAxios
Vuex.Store.prototype.$customAxios = customAxios

This solution has been effective for me.

You can now utilize this.$customAxios in your Vue and Vuex components.

Answer №2

To interact with the Vue instance within the store, you can simply use this._vm.

this._vm.$http.post()

Answer №3

One issue that frequently arises is the unavailability of $http within vuex. More information can be found at

It's important to note that state modifications should only occur in mutations, not actions. If you need to change the state from an action, simply commit a mutation to make the necessary alteration.

I encountered this same problem last night and received error messages indicating that async fetching should be done in actions triggering mutations. Async operations cannot be performed in mutations, and state alterations should not take place in actions, hence the need to separate the code accordingly.

// Example in actions
addStyle ({ commit, state }, newStyleObj) {
    console.log(newStyleObj);
    var vm = this;
    this.$http.post('http://localhost:16339/api/Styles/PostStyle/', newStyleObj)
        .then(response => {
            commit("setTableStyles", response.body);
            console.log(state.tableStyles)
            console.log(response.body)
        }, error => {
            console.log(error);
        });
}

// Example in mutations
setTableStyles(state, payload){
state.tableStyles = payload; // or state.tableStyles.push(...payload) if tableStyles is an Array 
}

Answer №4

When working outside of a Vue instance, such as with the `store` variable, make sure to use `Vue.http` (without the dollar sign). However, when inside an instance, you should use `this.$http` instead.

For more information, check out the Vue Resource documentation on GitHub.

Answer №5

integration of axios using Vue.prototype.$http

handleLogin({commit}, loginData) {
            return new Promise((resolve, reject) => {
                commit('auth_request');
                Vue.prototype.$http({url: '/user/login', data: loginData, method: 'POST'})
                    .then(response => {
                        const token = response.data.data.token;
                        const user = response.data.data.profile;
                        localStorage.setItem('token', token);
                        localStorage.setItem('user', JSON.stringify(user));
                        Vue.prototype.$http.defaults.headers['Authorization'] = 'Bearer ' + token;
                        this.state.user = JSON.parse(localStorage.getItem('user')) || '';
                        this.state.token = localStorage.getItem('token') || '';
                        commit('auth_success', {token, user});
                        resolve(response)
                    })
                    .catch(error => {
                        commit('auth_error');
                        localStorage.removeItem('token');
                        localStorage.removeItem('user');
                        reject(error)
                    })
            })
        },

Answer №6

One way to access vue Properties is by using this method:

this._vm.$yourDesiredPropertyName
. An example of this would be this._vm.$http. I found success with this approach. You will be able to access all properties that have been properly registered to the vue instance.

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

Ways to retrieve information from a different website's URL?

Having a bit of an issue here. I'm currently browsing through some reports on webpage #1 () and I have a specific requirement to extract the object named "data" from webpage #2 (). However, the code I've used seems to fetch the entire webpage ins ...

The button transforms once the user submits the form

I have two buttons labeled "Save" and "Saving..." <div ng-switch on="isLoading"> <div ng-switch-when="true"> <button type="button" class="btn btn-primary btn-block disabled">Saving ...</button> </div> <div ng-switch- ...

I am confused as to why my function is selecting all the checkboxes when it should only be selecting one

I am facing an issue while creating a list with checkboxes in reactJS. Whenever I click on a single checkbox, all the checkboxes get selected instead of just the one that was clicked. How can I resolve this problem? const checkHandler = () => { if ( ...

What is the most effective method for utilizing JSON as a database?

For my upcoming offline mobile web app project, I am considering using JSON to mirror some of my database tables and storing the data in localStorage. (Although Web SQL Database is an option, its future-proofing capabilities are questionable.) Initially, ...

NuxtJS project enhanced with MdBootstrap features

I'm currently trying to implement the Material Design components from a Vue resource (https://mdbootstrap.com/vue/) into my NuxtJS project, but I haven't been successful in finding clear instructions on how to do so. With Bootstrap-Vue, I was ab ...

Shift the element upwards instead of scrolling down the page

I'm struggling with a design challenge on my website. Currently, the page layout consists of a navigation bar, a header section, and the main body content. I'm trying to achieve a scrolling effect where the body content moves up and over the head ...

Steps for incorporating a smooth transition effect into a modal popup as its height dynamically increases

I need assistance with adding a transition effect to a modal popup that automatically increases in height when content is loaded. I have tried various styles, but none of them seem to be working. .tagModal{ overflow:hidden; transition:transform ...

The Bootstrap modal fails to appear when closed

After opening and closing the modal window, clicking on the button does not display the modal window again. The screen remains grayed out and the content of the modal window does not appear. yyyyyyyyyyyyyyyy function customShortcode() { ob_start(); ...

No output was generated by the emitted Typescript on Trading View

Currently, I am working with a combination of vuejs and nuxtjs for my project. I have been trying to incorporate Trading View into it, but when attempting to import the charting_library.min.d.ts file in the Vue component, an error is returned. Module bu ...

Is there a way to switch the video source when a particular h3 tag is clicked?

https://i.sstatic.net/I2gIZ.jpgI'm currently working on building a video streaming site, but I've hit a roadblock. My challenge right now is figuring out how to make the episode selector change the video player's source. I'm a bit conf ...

refreshing a javascript function without the need for reloading

Attempting to create an embedded web server using the Nano WiReach SMT. Here is the code that has been written so far: <HTML> <HEAD> <SCRIPT LANGUAGE=JavaScript> function swapImage() { var val1 ...

What is the best way to make one div show that another div is being toggled in a slideshow display?

I am searching for a solution to indicate when a div is being toggled, using a separate div with the class of ".bars". Experimented with if statements and modifying classes on the indicator div ".bars" to adjust its characteristics... The ".bars" indicat ...

Determine future dates based on selected date and time

When a user selects a date in the datetimepicker, I want to automatically set three additional dates. The first date will be the selected date + 28 days, the second date will be selected date + 56 days, and the third date will be selected date + 84 days. I ...

Challenges in Producing a Dynamic Table from a Pre-existing Table

Could you please review This Demo Fiddle and provide guidance on how to append values from selected row(s) by checkbox in a table to a new dynamic table? Here is what I have attempted: var td1 = []; $('#btn').on('click', function () { ...

Add new items to an array, with the most recent item being the last

I have encountered an issue while looping through an array of objects. Depending on their type property, I create a different class and append it to an array. However, the problem is that the output always consists of duplicates of the last class created. ...

Personalize the position of the v-select drop-down menu

I am currently working with the vuetify v-select component. The problem I am encountering is that instead of the dropdown opening downwards, I need it to open upwards since the dropdown is positioned at the bottom of the page which causes some of the dro ...

Incorporating the power of moment.js into your Vue.js

Hey there, I'm currently working on a project using Bootastrap-Vue along with JavaScript and I'm trying to incorporate Moment.js into my code. However, the time I am getting is not accurate. Can anyone help me out with this issue? Just a heads ...

Creating reusable components in Vue.js can enhance code reusability and make development

I am new to Vue.js and WebUI development, so I apologize in advance if I make any mistakes. Currently, I am exploring how to create reusable components using Vue.js. Specifically, I am working on a treeview component with the ability to customize the rend ...

The library "vue-property-decorator" (v10.X) is causing issues with resolving in Webpack despite being successfully installed

Encountered an error message Module not found: Error: Can't resolve './decorators/Emit' while attempting to import functionality from the library vue-property-decorator. The package is installed and accessible, ruling out a simple installati ...

Issue with displaying errors in vee-validate when using Vue.js Axios (More details provided)

When working on my Vue project, I encountered an issue while using Vee-Validate and Axios. During an API call to register a user, if the email is already in use, an error is thrown. To handle this error and display the error message, I used the following ...