refactor auth store
This commit is contained in:
parent
f6bc1dbad3
commit
4c96954764
@ -1,33 +1,7 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import axios, { AxiosResponse, Method } from "axios";
|
||||
import { getAuthToken, setAuthToken, useAuthStore } from "../stores/auth";
|
||||
|
||||
|
||||
interface AuthStore {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthStore>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
token: "",
|
||||
}),
|
||||
{
|
||||
name: "token",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const getAuthToken = () => useAuthStore.getState().token;
|
||||
|
||||
export const setAuthToken = (token: string) => useAuthStore.setState({ token });
|
||||
|
||||
export const clearAuthToken = () => useAuthStore.setState({ token: "" });
|
||||
|
||||
export function useToken() {
|
||||
return useAuthStore(state => state.token);
|
||||
}
|
||||
|
||||
export async function makeRequest<TRequest = unknown, TResponse = unknown>({
|
||||
method = "post",
|
||||
url,
|
||||
@ -94,4 +68,4 @@ function refresh(token: string) {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
6
src/hooks/useToken.ts
Normal file
6
src/hooks/useToken.ts
Normal file
@ -0,0 +1,6 @@
|
||||
import { useAuthStore } from "../stores/auth";
|
||||
|
||||
|
||||
export function useToken() {
|
||||
return useAuthStore(state => state.token);
|
||||
}
|
24
src/stores/auth.ts
Normal file
24
src/stores/auth.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
|
||||
|
||||
interface AuthStore {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthStore>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
token: "",
|
||||
}),
|
||||
{
|
||||
name: "token",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
export const getAuthToken = () => useAuthStore.getState().token;
|
||||
|
||||
export const setAuthToken = (token: string) => useAuthStore.setState({ token });
|
||||
|
||||
export const clearAuthToken = () => useAuthStore.setState({ token: "" });
|
1
src/stores/index.ts
Normal file
1
src/stores/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from "./auth";
|
Loading…
Reference in New Issue
Block a user