fix: adjust auth state and api

This commit is contained in:
Paul Pan 2024-02-22 18:47:51 +08:00
parent 733c817145
commit 1bf029ca65
3 changed files with 6 additions and 12 deletions

View File

@ -52,11 +52,11 @@ export const userApi = api.injectEndpoints({
}),
invalidatesTags: ["User", "Status", "Submission"],
}),
profile: builder.query<Wrap<UserProfile>, UserRequest>({
query: (data: UserRequest) => ({
profile: builder.query<Wrap<UserProfile>, number>({
query: (data: number) => ({
url: "/user/profile",
method: "POST",
body: data,
body: { uid: data },
}),
providesTags: ["User"],
}),

View File

@ -1,16 +1,13 @@
import { createSlice } from "@reduxjs/toolkit";
import type { UserProfile } from "../../app/services/user";
import { userApi } from "../../app/services/user";
import type { RootState } from "../../app/store";
type AuthState = {
profile: UserProfile | null;
token: string | null;
};
const initialState: AuthState = {
profile: null,
token: null,
token: localStorage.getItem("token"),
};
export const authSlice = createSlice({
@ -26,14 +23,11 @@ export const authSlice = createSlice({
builder
.addMatcher(userApi.endpoints.login.matchFulfilled, (_state, action) => {
// Login Success
console.log(action);
const { token } = action.payload.body;
localStorage.setItem("token", token);
return { profile: null, token: token };
})
.addMatcher(userApi.endpoints.profile.matchFulfilled, (state, action) => {
// Profile Success
return { ...state, profile: action.payload.body };
})
.addMatcher(userApi.endpoints.logout.matchFulfilled, (_state, _action) => {
// Logout Success
localStorage.removeItem("token");

View File

@ -4,5 +4,5 @@ import { useAppSelector } from "./store";
export const useAuth = () => {
const auth = useAppSelector(selectCurrentUser);
return useMemo(() => ({ token: auth.token, profile: auth.profile }), [auth]);
return useMemo(() => ({ token: auth.token }), [auth]);
};