feature/state-and-data-fetching #1
@@ -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),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
Reference in New Issue
Block a user