feat(auth): add refresh action to authStore

This commit is contained in:
Ilia Mashkov
2026-03-17 14:18:49 +03:00
parent 226874bbec
commit b75e805f54
2 changed files with 27 additions and 1 deletions

View File

@@ -1,6 +1,6 @@
import { create } from "zustand"; import { create } from "zustand";
import type { AuthStore, AuthStoreState } from "../../types/store"; import type { AuthStore, AuthStoreState } from "../../types/store";
import { login, logout, register } from "../../../api"; import { login, logout, refresh, register } from "../../../api";
import { callApi } from "shared/utils"; import { callApi } from "shared/utils";
import { UNEXPECTED_ERROR_MESSAGE } from "shared/config"; import { UNEXPECTED_ERROR_MESSAGE } from "shared/config";
@@ -83,4 +83,28 @@ export const useAuthStore = create<AuthStore>()((set) => ({
set({ error: new Error(UNEXPECTED_ERROR_MESSAGE) }); set({ error: new Error(UNEXPECTED_ERROR_MESSAGE) });
} }
}, },
refresh: async () => {
set({ status: "loading" });
try {
const [responseData, refreshError] = await callApi(() => refresh());
if (refreshError) {
set({ status: "unauthenticated", error: refreshError });
return;
}
set({
status: "authenticated",
user: responseData?.user,
accessToken: responseData?.accessToken,
error: null,
});
} catch (err) {
console.error(err);
set({
status: "unauthenticated",
error: new Error(UNEXPECTED_ERROR_MESSAGE),
});
}
},
})); }));

View File

@@ -24,12 +24,14 @@ export interface AuthStoreState {
export type LoginAction = (data: AuthData) => void; export type LoginAction = (data: AuthData) => void;
export type RegisterAction = (data: AuthData) => void; export type RegisterAction = (data: AuthData) => void;
export type LogoutAction = () => void; export type LogoutAction = () => void;
export type RefreshAction = () => void;
export interface AuthStoreActions { export interface AuthStoreActions {
// Async actions // Async actions
login: LoginAction; login: LoginAction;
register: RegisterAction; register: RegisterAction;
logout: LogoutAction; logout: LogoutAction;
refresh: RefreshAction;
} }
export type AuthStore = AuthStoreState & AuthStoreActions; export type AuthStore = AuthStoreState & AuthStoreActions;