Troubleshooting Vue.js and Axios: Request Transformation Issue Resulting in Undefined Data

I recently implemented transformRequest and transformResponse functions to display a loader while my data is rendering. However, after adding these functions, I noticed that my POST and PATCH requests are not functioning properly. There are no error messages in the console, but whenever I try to modify an entity using a PATCH request, nothing happens. Removing the transformRequest function allows me to successfully send POST and PATCH requests.

Could someone please help me identify what went wrong?

UPDATE! Below is the excerpt from http/index.js:

...
transformRequest(data) {
 console.log(data); // returns undefined
 store.dispatch('loadingData');
 console.log(data) // returns undefined
 return console.log(JSON.stringify(data)); // returns undefined
},
transformResponse(data) {
 store.dispatch('finishLoadingData');
 const parsedData = JSON.parse(data);
 if (parsedData.error === 'Access denied') {
   cookies.remove('access_token');
   window.location = `${config.mainSite}/login`;
 }
 return parsedData;
},
...

Here's the information related to the store:

export default {
 state: {
  loading: false,
 },
 actions: {
  loadingData({ commit }) {
   commit('LOADING_DATA');
 },
 finishLoadingData({ commit }) {
   commit('FINISH_LOADING_DATA');
 },
},
mutations: {
 LOADING_DATA(state) {
  state.loading = true;
 },
 FINISH_LOADING_DATA(state) {
  state.loading = false;
 },
},
getters: {
  getLoading(state) {
   return state.loading;
  },
 },
};

Answer №1

When utilizing Axios, it's important to note that both transformRequest and transformResponse expect an array of functions rather than just a single function. Consider implementing the following approach:

...
transformRequest: [(data) => {
    store.dispatch('loadingData');

    return data;
}],

transformResponse: [(data) => {
    store.dispatch('finishLoadingData');

    const parsedData = JSON.parse(data);

    if (parsedData.error === 'Access denied') {
        cookies.remove('access_token');
        window.location = `${config.mainSite}/login`;
    }
    return parsedData;
}],
...

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

Vue router is unable to verify the user's authentication

I have certain app routes that are supposed to be restricted to admins only. I've added requiresAdmin: true, to the meta of those routes, but for some reason it doesn't prevent other users from accessing them. Code Note: I've included comme ...

Tips on storing JSON string array with multiple name/value pairs in distinct arrays using JavaScript

Below is a JSON string that I have: [ { "id" : "1", "name" : "name1" }, { "id" : "2", "name" : "name2" }, { "id" : "3", "name" : "name3" }, { "id" : "4", "name" : "name4" }, { "id" : "5", "name" : "name5" } ] Is there a way to split this data into two se ...

Deciphering JSON encoded information within a Vue Component

When passing JSON encoded data to my Vue component as a prop, the data is successfully received but I am having trouble parsing it. profile.blade.php @extends('layouts.app') @section('content') <my-profile user-details="{{ js ...

Strapi GraphQL mutation encountered an issue: String not properly closed

Whenever I attempt to update my database using the JavaScript Strapi SDK, I encounter the error message "Syntax Error: Unterminated string". The this.chapter.content variable contains an HTML string generated by CKEditor. How can I properly escape this s ...

What is the best way to streamline this using Javascript or jQuery?

Looking for a way to simplify the code for 4 vertical sliding panels? Check out the following script: $(".sliding-panels").click(function() { var n = $(this).attr("number"); var panels = $(".panel"); panels.not(".panel" + n).removeClass("pa ...

Displaying an undefined value using ExpressJs (to present an [object])

While learning expressjs, I encountered an issue where the value I passed did not appear in the output. I created a new Routes file and defined a function with Route methods in it. However, when I set Route paths, the value did not show up in the output. A ...

An error has occurred as ByChained is not recognized

Recently, I have been experimenting with selenium webdriverjs in javascript to locate an element that includes the partial text "hoi" as well as the text "hoe gaat het". I attempted to use ByChained for this purpose, but encountered an error stating that ...

What distinguishes between the methods of detecting falsy and truthy values?

While working with JavaScript / Typescript, I often find myself needing to verify if a length exists or if a value is true or false. So, the main query arises: are there any differences in performance or behavior when checking like this... const data = [ ...

Using v-for to show the values of an object in Vuetify

I am currently developing a function in vuejs that allows users to select tables from a database, with the columns' names automatically appearing in a v-list-item component. However, I am facing difficulty in displaying these column names effectively. ...

Interactive table on click

Seeking assistance with an issue involving a combobox (select) and a dynamic table generated from PHP. The table displays names along with their Firstname, Lastname, and ID (hidden). Upon clicking on a row in the table, I should retrieve the ID of that spe ...

Retrieving Data from a JSON Object Using a Specific Key

Received a JSON response similar to the one below { "SNGS": { "$": { "xmlns": "csng", "xmlns:ns2": "http://www.w3.org/1999/xlink" }, "Defec ...

Transforming a REST API get call into GraphQL

I'm currently using a REST API that accepts a code parameter, searches the database for matches, returns results if the parameter exists, and redirects users to a long_url retrieved from the database. How can I convert this functionality to GraphQL? i ...

Tips for prioritizing new data input at the top of the list

Hey there, I'm having trouble figuring out how to push new data to the top of a list using vue.js and laravel. I've been trying but haven't had any luck so far. If anyone could lend a hand, I would greatly appreciate it. Below is my Control ...

Refresh the Data Displayed Based on the Information Received from the API

As someone who is relatively new to React, I have been making progress with my small app that utilizes React on the frontend and a .NET Core API on the server-side to provide data. However, I have encountered a problem that I've been grappling with fo ...

Move the focus to the previous input field by removing the key

I have created a phone number input with 10 fields that automatically skip to the next field when you fill in each number. However, I would like to be able to go back to the previous field if I make a mistake and need to delete a digit. How can I achieve ...

Issue with the position of the search dropdown in HTML

When we click on the Dropdown option, it appears above the text instead of below. I have been trying to fix the positioning issue where the Dropdown shows up separately after clicking, but I have not been successful so far. Maybe you can offer some assist ...

Vue.js: Dynamically set button activation based on array size

I have been attempting to enable or disable a button based on the length of an array, and here is my code: <button class="submit-button" type="button" v-on:click="DoSomething()" :disabled="array.length > 0">Submit</butt ...

Acquire an image from the database using Node.js

I have successfully implemented a file upload functionality and saved the path in MongoDB. Now, I am facing an issue while trying to display the uploaded image in HTML. Below is the code snippet for uploading the file: route.post('/dashboard/upload&a ...

What is the best way to prevent the content within a div from being obscured by a sticky element affixed to the bottom of the div?

I am struggling with ensuring that the content in my wrapper does not get cut off by the "view more" div attached to the bottom. The default wrapper cuts off the children, and even when expanded, the issue persists due to CSS problems. In React, the gener ...

Save data in a function

I have a functionality in place that processes data received from a server through websocket. Depending on the specific page being accessed, the data is handled differently. sock.onmessage = function (e) { log(e.data); } function returnCurrentPage(m) ...