Skip to content

Commit

Permalink
fix: fix the auth hook
Browse files Browse the repository at this point in the history
  • Loading branch information
Sampiiiii committed Apr 20, 2024
1 parent 9830454 commit f2fe368
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
4 changes: 4 additions & 0 deletions apps/forge/src/hooks/useVerifyAuthentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useDispatch } from "react-redux";
import { User } from "@ignis/types/users.ts";
import axiosInstance from "@/api/axiosInstance.ts";
import { userActions } from "@/redux/user.slice.ts";
import { authActions } from "@/redux/auth.slice.ts";

export const useVerifyAuthentication = () => {
const [loading, setLoading] = useState(true);
Expand All @@ -15,12 +16,15 @@ export const useVerifyAuthentication = () => {
const response = await axiosInstance.get("/users/me");
if (response.status === 200) {
dispatch(userActions.setUser(response.data));
dispatch(authActions.onLogin());
setUser(response.data);
} else {
dispatch(authActions.onLogout());
setUser(null);
}
} catch (error) {
setUser(null);
dispatch(authActions.onLogout());
} finally {
setLoading(false);
}
Expand Down
14 changes: 14 additions & 0 deletions apps/forge/src/redux/auth.slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { AuthState } from "@/types/auth.ts";

// Define initial state based on persisted state or default values
const initialState: AuthState = {
is_authenticated: false,
is_loading: false,
redirect: undefined,
};

Expand All @@ -14,6 +16,18 @@ const authSlice = createSlice({
setRedirect: (state, action: PayloadAction<string>) => {
state.redirect = action.payload;
},
setIsLoading: (state, action: PayloadAction<boolean>) => {
state.is_loading = action.payload;
},
onLogin: (state) => {
state.is_authenticated = true;
state.is_loading = false;
},
onLogout: (state) => {
state.is_authenticated = false;
state.is_loading = false;
state.redirect = undefined;
},
},
extraReducers: (builder) => {
builder.addCase(RESET_APP, () => initialState);
Expand Down
2 changes: 2 additions & 0 deletions apps/forge/src/types/auth.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export interface AuthState {
is_authenticated: boolean;
is_loading: boolean;
redirect?: string;
}

0 comments on commit f2fe368

Please sign in to comment.