Different ways to separate an axios call into a distinct method with vuex and typescript

I have been working on organizing my code in Vuex actions to improve readability and efficiency. Specifically, I want to extract the axios call into its own method, but I haven't been successful so far.

Below is a snippet of my code:

async updateProfile({ commit, dispatch }: any, user: User):Promise<User> {
    console.log(user)
    console.log("currentUser")

    const response = await axios.request({
        method: "PUT",
        url: `/users/me/profile`,
        data: user
    });
  
    console.log(response)
    console.log("response")
    return user;
},
async updateUserProfile(user: any): Promise<User> {
    return await axios.request({
        method: "PUT",
        url: `/users/me/profile`,
        data: user
      });
},

The commented-out line where dispatch is being called to update the user profile results in a 400 error when I replace it with axios.request. Additionally, changing 'user: any' to 'user: User' triggers an incompatible property type error pertaining to 'actions'.

Answer №1

There is a discrepancy in your URLs - one contains a leading slash while the other does not. Additionally, your second action should have `{}` as the first parameter instead of being left blank. It should read `async updateUserProfile({}, user: any)`. This could be the reason for receiving a 400 error. Is your request payload possibly empty?

Answer №2

Have you defined both updateProfile and updateUserProfile as actions in vuex? It seems like the latter may not be an action at all; remember, the first argument for all actions is the context.

You could consider making it a standalone function, completely separate from your store.

// This function could even reside in another file or module
const updateUserProfile = (user: User) =>
  axios.put<User>("/users/me/profile", user)

Then, in your action, you would simply call this function directly

// S = state type, R = root state type
async yourAction({ commit }: ActionContext<S, R>, user: User): Promise<User> {
  const response = await updateUserProfile(user)
  
  // This is where you would commit something
  
  return user // or whatever value you need to return
}

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

Determine the specific data types of the component properties in React Storybook using TypeScript

Currently, I am putting together a component in the storybook and this is how it appears: import React, { useCallback } from 'react'; import { ButtonProps } from './types'; const Button = (props: ButtonProps) => { // Extract the nec ...

Definition of Promise resolve type in Visual Code's d.ts file

Need help with: // api.js export function getLayout(){ return axios.get('/api/layout').then(res => res.data) } // api.d.ts declare interface JSONResponse { meta: object, data: Array<Field> } export declare function getLayout ...

Is there Polyfill Compatibility for Custom Elements in Angular 9?

When it comes to polyfilling support for custom elements created with Angular, there are various recommendations available. This demo demonstrates that adding the following polyfill in polyfills.ts works: import '@webcomponents/webcomponentsjs/custo ...

What is the purpose of exporting both a class and a namespace under the same name?

While exploring some code, I came across a situation where a class and a namespace with identical names were exported from a module. It seems like the person who wrote this code knew what they were doing, but it raised some questions for me. Could you shed ...

Leverage Springs with TypeScript

function createDefaultOrder(items: any[]): number[] { return items.map((_, index) => index); } type CustomHandler<T> = (index: number) => T; type CustomValues = { zIndex: number, y: number, scale: number, shadow: number, immediate: ...

I thought enabling CORS would solve the issue, but it seems like the restrictions

This is my setup for an asp.net core web API: public void ConfigureServices(IServiceCollection services) { services.AddCors(o => o.AddPolicy("CorsPolicy", builder => { builder ...

How to reference an object from an external file in TypeScript using Ionic 2 and Angular 2

I am currently developing a mobile application with Ionic2 and have integrated a simple online payment service called Paystack for processing payments. The way it operates is by adding a js file to your webpage and then invoking a function. <script> ...

What is the best way to determine the type of `rootReducer`?

My project is set up with a combination of React, Redux, Immutable.js, and TypeScript. As I worked on implementing it, I made an effort to declare types wherever possible which led me to discover an interesting issue. A code example illustrating the proble ...

Leverage the power of TypeScript by enabling the noImplicitAny flag when working

Currently, I am looking to activate the noImplicitAny flag in my compiler. My main issue lies with utilizing lodash/fp as there are no typings available at this moment. Due to this, the compiler is generating errors due to the absence of a definition file ...

Align item in center of remaining space within container using Material-UI React

I am relatively new to MUI and styling HTML components, and I have a query. I'm currently utilizing the Grid feature in my React project. My goal is to achieve something similar to this (image edited in Paint, alignment may not be accurate): https://i ...

Transferring information between screens in Ionic Framework 2

I'm a beginner in the world of Ionic and I've encountered an issue with my code. In my restaurant.html page, I have a list of restaurants that, when clicked, should display the full details on another page. However, it seems that the details for ...

Transforming an array of objects into individual objects using Vue.js and PHP

Is there a way to convert this object into an array of objects? [ [ { "fieldName": "4579043642", "message": "set number '4579043642' exists!" } ], [ { & ...

Using LitElement: What is the best way to call functions when the Template is defined as a const?

When the template is defined in a separate file, it's not possible to call a function in the component. However, if the template is defined directly as returning rendered HTML with this.func, it works. How can one call a function when the template is ...

Invoke a function and assign it to an export variable

I have a query regarding a file containing an export constant that is utilized to construct a navigation bar in CoreUI. However, I am exploring methods to generate dynamic JSON data within other Components or the same file and then inject it into the exp ...

Deleting the v-stepper-header number with Vuetify

I have been searching everywhere in an attempt to resolve this issue, but I have not been able to find a solution. Is there a way to remove the numbers from the v-stepper-header? - Using Vuetify version: 1.5.6 Current: https://i.stack.imgur.com/gLxFX.png ...

Convert individual packages within the node_modules directory to ES5 syntax

I am currently working on an Angular 12 project that needs to be compatible with Internet Explorer. Some of the dependencies in my node_modules folder are non es5. As far as I know, tsc does not affect node_modules and starts evaluating from the main opti ...

Using Vue Js to bind two values to an href attribute in a tag

As a Vue.js beginner, I am encountering an issue where I need to update two values simultaneously during rendering. <ul class="category-list"> <li v-for="category in categories"> <a v-bind:href="location/category.slug/all" v-tex ...

Learn how to dynamically import external modules or plugins using the import() functionality of TypeScript 2.4 within the production script generated by Angular CLI

Utilizing the typescript 2.4 [import()][1] feature has proven to be effective for dynamically loading modules. Testing this functionality has shown positive results, especially when importing modules and components located within the same directory. Howev ...

Encountering Vue Router Error while integrating Laravel 9 with Vite and Vue CLI 3

I am struggling to fix it, please assist me. I can't seem to pinpoint the issue and need some guidance. Error Image Links: https://i.stack.imgur.com/VhVXL.png https://i.stack.imgur.com/IENFm.png ...

Developing a custom feature with a ListView in nativescript-vue

Currently, I am immersing myself in the world of nativescript-vue and exploring ways to utilize single file components for enhancing the cleanliness of my code. To kickstart this endeavor, I initiated with a straightforward example that showcases beautiful ...