Vue: Set user in vuex store before registration


Hi Stackoverflow Community,

I have a Vue.js application where a user can register. The registration is displayed in three different components. Register 1 (email, password), Register 2 (personal information) and Register 3 (preferences).

I implemented an api post request after the user press register on the first page according to bezkoder: https://www.bezkoder.com/vue-3-authentication-jwt/

What I am trying to do now is instead of register the user directly, I want to save the user data in my vuex store and send the api post request in Register 3 instead of Register 1, when I have all the user information.

Unfortunately, I am not able to create a new state in my store. This is my auth.module.js Code (store):

import AuthService from "../services/auth.service";
const user = JSON.parse(localStorage.getItem("user"));

const initialState = user
  ? { status: { loggedIn: true }, user }
  : { status: { loggedIn: false }, user: null };

export const auth = {
  namespaced: true,
  state: initialState,

  actions: {
    login({ commit }, user) {
      return AuthService.login(user).then(
        (user) => {
          commit("loginSuccess", user);
          return Promise.resolve(user);
        },
        (error) => {
          commit("loginFailure");
          return Promise.reject(error);
        }
      );
    },
    logout({ commit }) {
      AuthService.logout();
      commit("logout");
    },
    register({ commit }, user) {
      return AuthService.register(user).then(
        (response) => {
          commit("registerSuccess");
          return Promise.resolve(response.data);
        },
        (error) => {
          commit("registerFailure");
          return Promise.reject(error);
        }
      );
    },
  },
  mutations: {
    loginSuccess(state, user) {
      state.status.loggedIn = true;
      state.user = user;
    },
    loginFailure(state) {
      state.status.loggedIn = false;
      state.user = null;
    },
    logout(state) {
      state.status.loggedIn = false;
      state.user = null;
    },
    registerSuccess(state) {
      state.status.loggedIn = true;
    },
    registerFailure(state) {
      state.status.loggedIn = false;
    },
  },
};

So I need to create a state for my userdata (email, password, preferences) and then an action and a method to save my userdata from Register 1 and 2.

Does someone has a clue how I could implement this? Or do you have a better idea how to create my registration?

Glad for all your tips and tricks 🙂

Source: Vue – Stack Overflow

November 26, 2021
Category : News
Tags: javascript | state | Vue.js | vuex

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.