Home > other >  How to move an axios call into its own method using vuex and typescript
How to move an axios call into its own method using vuex and typescript

Time:11-30

I have a method in vuex actions that calls the api and updates the user information. What I am trying to do is move the axios call into its own method and have not had any luck.

Here is 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
    });
    //  dispatch('updateUserProfile', user);
   
    console.log(response)
    console.log("response")
    return user;
    // return response;
},
async updateUserProfile(user: any): Promise<User> {
    return await axios.request({
        method: "PUT",
        url: `/users/me/profile`,
        data: user
      });
},

The line commented out dispatch is trying to call the axios method and pass the user as a parameter. When I try that line instead of the axios.request I get a 400 error. When I change user: any to user: User I get an Types of property 'actions' are incompatible. error

CodePudding user response:

Your URLs are different. One has a leading slash, the other one hasn't. And your second action should have {} as first param. Should be async updateUserProfile({}, user: any). This probably explains why you're getting a 400. Your request payload is probably empty, isn't it?

CodePudding user response:

Are you defining both updateProfile and updateUserProfile as vuex actions? If so, the latter doesn't look like an action at all; the first arg for all actions is the context.

Just make it a stand-alone function, separate from your store entirely

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

From an action, you would just call this directly

// S = state type, R = root state type
async yourAction({ commit }: ActionContext<S, R>, user: User): Promise<User> {
  const response = await updateUserProfile(user)

  // here's where you would commit something

  return user // or whatever
}
  • Related