All files / src/stores authStore.ts

100% Statements 29/29
100% Branches 7/7
100% Functions 6/6
100% Lines 29/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 401x 1x                     1x 1x 1x 14x 14x 14x 14x 14x 14x 8x 8x 8x 8x 8x 14x 1x 1x 1x 79x 79x 79x 1x 14x 14x 1x 1x 1x  
import { create } from "zustand";
import { persist } from "zustand/middleware";
 
interface AuthState {
  user: { id: string; email: string } | null;
  isAuthenticated: boolean;
  hasHydrated: boolean;
  setUser: (user: { id: string; email: string } | null) => void;
  setHasHydrated: (hydrated: boolean) => void;
  logout: () => void;
}
 
export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      user: null,
      isAuthenticated: false,
      hasHydrated: false,
      setUser: (user) => set({ user, isAuthenticated: !!user }),
      setHasHydrated: (hydrated) => set({ hasHydrated: hydrated }),
      logout: () => {
        localStorage.removeItem("access_token");
        localStorage.removeItem("refresh_token");
        localStorage.removeItem("token_expires_at");
        set({ user: null, isAuthenticated: false });
      },
    }),
    {
      name: "auth-storage",
      partialize: (state) => ({
        user: state.user,
        isAuthenticated: state.isAuthenticated,
      }),
      onRehydrateStorage: () => (state) => {
        state?.setHasHydrated(true);
      },
    },
  ),
);