issue with class methods / async?

57 Views Asked by At

Using Zustand in my React project, I am defining the global authentication states as you see in the code snippet. I am also defining an Auth API to run the auth methods. However, for some strange reason, even when the response status is 200 and when I make it into the if (response.status === 200) check, the if-block lines after the this.setLogin line do not run, which means: success=true does not run. console.log("authenticated") also does not run. If I put them before the this.setLogin, they both run.

The Zustand store:

import { create } from "zustand";

type AuthStore = {
  id: number | null;
  isLoggedIn: boolean;
  accessToken: string;
  setLogin: (token: string, id: number) => void;
  setLogout: () => void;
  test: () => void;
};

export const useAuthStore = create<AuthStore>((set) => ({
  id: null,
  isLoggedIn: false,
  accessToken: "",
  setLogin: (token, id) =>
    set({ isLoggedIn: true, accessToken: token, id: id }),
  setLogout: () => set({ isLoggedIn: false, accessToken: "", id: null }),
  test: () =>
    set((state) => {
      console.log(state.accessToken);
      return {};
    }),
}));

The auth API:

import { AxiosResponse, isAxiosError } from "axios";
import { UserAccountType } from "../types/userInfo.type";
import api from "./api";
import { useAuthStore } from "../store/authStore";

interface User {
  token: string;
  id: number;
}

export class AuthApi {
  private static setLogin(token: string, id: number): void {
    useAuthStore().setLogin(token, id);
  }

  static async login(userCred: Partial<UserAccountType>) {
    let success = false;
    let errorMessage = "";
    try {
      const response = await api.post<User>("/auth/login", userCred, {
        withCredentials: true,
      });
      if (response.status === 200) {
        const token = response.data.token;
        const id = response.data.id;
        this.setLogin(token, id);
        console.log("authenticated");
        success = true;
      }
    } catch (err) {
      if (isAxiosError(err)) {
        const status = err.response?.status;
        console.log(err);
        switch (status) {
          case 401:
            errorMessage =
              "Invalid Email or Password. Try again or click Forgot password to reset it.";
            break;
          default:
            errorMessage = `${err.message}. Please try again.`;
        }
      }
    }

    return { success, errorMessage };
  }
}
0

There are 0 best solutions below