Can the Vue instance be accessed in Axios interceptors?

I've integrated vue-reactive-storage to have a reactive alternative to localStorage in my Vue application. This plugin creates a vue object that is accessible to all components. I'm facing an issue when trying to access this object within my axios interceptors response function, as I keep getting the error message

TypeError: Cannot read property 'localStorage' of undefined
.

Here's a snippet from my app.js:

require('./bootstrap');

import Vue from 'vue';
import Vuetify from 'vuetify';
import reactiveStorage from "vue-reactive-storage";
import store from './store/index';

Vue.use(Vuetify);
Vue.use(reactiveStorage, {
  "snackBar": {show: false, text: '(Initial snackbar text.)', type: 'info', timedelay: 2000},
});

axios.interceptors.response.use(response => response, error => {
    this.localStorage.snackBar.text = error.response.data.message || 'Request error status: ' + error.response.status,
    this.localStorage.snackBar.type = 'error'
    this.localStorage.snackBar.show = 'true'
})

import router from './routes';

const app = new Vue({
    el: '#app',
    vuetify: new Vuetify(),
    router,
    store,
    }
});

Is there a way around this issue?

This setup is on Laravel v6.4.1 and Vue v2.6.10.

Answer №1

Have you considered leveraging the power of Vuex store? It offers reactivity that can greatly benefit your project. Additionally, integrating a plugin for interceptors is quite simple as shown below:

export default function ({ $axios, store, redirect, context }) {
    $axios.onResponse(response => {
    // Insert your code here
    store.commit('set_sample_data', response.data)
})
}

Answer №2

You can achieve this by utilizing a traditional function declaration and assigning it to the prototype, allowing the function to inherit the context binding of your Vue instance. More details can be found here.

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

Attempting to retrieve a state object within the mounted lifecycle hook of my Vue component

My Vuex state contains a user ID, but whenever I try to access it in the mounted() lifecycle hook of my component, it is always returning as null. Is there a way to properly use the state stored in my computed property using mapGetters inside the mounted( ...

Can ajax requests be made without a web browser?

Currently, I am in the process of developing JavaScript tests using mocha and chutzpah, which means conducting all my tests without a browser. However, I have encountered an issue where all my AJAX calls are resulting in empty strings. Even when using the ...

Guide to transferring a PHP variable from a loop and converting it into a JavaScript variable

I am having an issue with accessing specific row values in a while loop that displays data from a mysql table into a table. Each row has a button to send data via ajax to another PHP page for insertion into another table. However, since I am outside of the ...

How can we avoid multiple taps on Ext.Button in Sencha Touch?

Currently working on a Sencha Touch game, but struggling with users tapping buttons multiple times. Looking for a simple solution to prevent multiple tap events in the app.js file so that only one tap event is executed even if a user taps or presses for an ...

Failure in Retrieving Fresh Information via Ajax Call

My web application utilizes polling to constantly update the status of a music player. To achieve this, I have implemented a method using setInterval to execute an Ajax call every half second. This setup functions as intended on a variety of browsers inclu ...

Refresh Form (Reactive Forms)

This is the HTML code snippet: <div class="container"> <ng-template [ngIf]="userIsAuthenticated"> <form [formGroup]='form' name="test"> <div class="form-group"> <input type="text" class="form-contr ...

Executing functionality based on changes in Angular bindings

I am working on securing user passwords in my HTML form. Currently, the password field is stored in localstorage like this: In JS: $scope.localStorage = localStorage; And then in HTML: <input id="pass" type="password" ng-model="localStorage.pass" re ...

Transferring PHP and JavaScript variables via AJAX to PHP page and storing in MySQL database table

After searching through numerous similar questions, I still haven't found the exact answer I need. I have a set of js variables that are sent via ajax to a location.php file, where they will be inserted into a mysql table. The current ajax call looks ...

Link together a series of AJAX requests with intervals and share data between them

I am currently developing a method to execute a series of 3 ajax calls for each variable in an array of data with a delay between each call. After referring to this response, I am attempting to modify the code to achieve the following: Introduce a del ...

Youtube video embedding showing cut edges on smaller screens

Looking for assistance with a Next.js and tailwind site I am building. Having trouble getting the video component to display properly on mobile screens. Tried various fixes but the video still gets cut off on smaller screen sizes. If anyone has a soluti ...

Get the username from Parse instead of using the ObjectID

When using angular and Parse for JavaScript, I have implemented a search field where an admin can input the objectid of a user to display their details. However, I would like to modify this functionality so that the admin can enter the username instead of ...

Switch the ng-bind-html option

Dealing with a string in my scope, I must determine whether I want the HTML escaped or not. A boolean value helps to decide if the HTML should be escaped or left as is. Snippet Check out some of my code examples below: $scope.result = "<b>foo</ ...

Variable remains unchanged by method

I am currently working on an app that utilizes the user's webcam. In case navigator.getUserMedia fails, I need to change the error variable to display the appropriate error message instead of the stream output. Since I am new to Vue, please bear with ...

Determining the worth of radio buttons, dropdown menus, and checkboxes

I am working on designing a menu for a pizza place as part of a learning project. The menu allows users to select their pizza size from small, medium, and large using radio buttons, and then customize it further with three select boxes where each selection ...

Utilizing ReactJS and Gatsby Js: How to pass the value of a child component to the parent component to create a button

In my current project, I am facing an issue with a simple component that is supposed to pass back the link value from the child component to a function in the parent component. However, it seems to only call back the full function instead of its actual v ...

Ways to troubleshoot and resolve the jQuery error with the message "TypeError: 'click' called"

I am currently developing a project for managing Minecraft servers, focusing on a configuration panel. I have set up a form that users need to fill out in order to configure the settings and send the values using Ajax. However, I encountered an error: Type ...

Exploring Next.js with getServerSideProps

My code has a warning from the console attached. I would appreciate it if someone could help me identify the problem... When I use the "data" hardcoded as props, I can display them in the components, but when I try to fetch from an API, I can retrieve the ...

When going through an array using jquery, only the final object is returned

I am diving into the world of jQuery and dealing with what seems to be a basic issue. <input type="text" name="text1" value=""></input> <input type="text" name="text2" value=""></input> <input type="text" name="text3" value=""&g ...

Is there a way to incorporate electron methods within Svelte files, specifically in Svelte 3, or is there an alternative approach to achieve this integration?

Currently, I am deep into a project that involves Svelte 3 and Electron 12.0.5 working together harmoniously. For managing hash routing, I have integrated the svelte-spa-router package into my setup. Here is a glimpse of how my project structure appears: n ...

Utilizing various AngularJS filters with multiple input sources

Looking to enhance my user array filtering process with two input boxes. Here's how the array is structured: $scope.users = [{ id: 1, fname: 'Sophia', lname: 'Smith', email: '<a href="/cdn-cgi/l/email ...