another step
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
'use client';
|
||||
import { createContext, useContext, useReducer } from 'react';
|
||||
import type { Dispatch, FunctionComponent, PropsWithChildren } from 'react';
|
||||
import { authReducer } from './authReducer';
|
||||
import { INITIAL_AUTH_STATE } from './types';
|
||||
import type { AuthAction, AuthState } from './types';
|
||||
|
||||
export type AuthContextValue = [AuthState, Dispatch<AuthAction>];
|
||||
|
||||
const AuthContext = createContext<AuthContextValue>([INITIAL_AUTH_STATE, () => null]);
|
||||
|
||||
interface AuthProviderProps extends PropsWithChildren {
|
||||
// Auth state resolved on the server from the request's access-token cookie.
|
||||
// Seeding the reducer with it means the first client render already reflects
|
||||
// the real session — no logged-out flash, no post-mount cookie read.
|
||||
initialState?: AuthState;
|
||||
}
|
||||
|
||||
export const AuthProvider: FunctionComponent<AuthProviderProps> = ({ initialState, children }) => {
|
||||
const value = useReducer(authReducer, initialState ?? INITIAL_AUTH_STATE);
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
};
|
||||
|
||||
export const useAuth = (): AuthContextValue => useContext(AuthContext);
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Reducer } from 'react';
|
||||
import type { AuthAction, AuthState } from './types';
|
||||
|
||||
export const authReducer: Reducer<AuthState, AuthAction> = (state, action) => {
|
||||
switch (action.type) {
|
||||
case 'LOG_IN':
|
||||
return { isAuthenticated: true, currentUser: action.user ?? state.currentUser };
|
||||
case 'LOG_OUT':
|
||||
return { isAuthenticated: false };
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
export { AuthProvider, useAuth } from './AuthContext';
|
||||
export type { AuthContextValue } from './AuthContext';
|
||||
export { INITIAL_AUTH_STATE } from './types';
|
||||
export type { AuthAction, AuthState } from './types';
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { User } from '@/services/auth/types';
|
||||
|
||||
export interface AuthState {
|
||||
isAuthenticated: boolean;
|
||||
currentUser?: User;
|
||||
}
|
||||
|
||||
export type AuthAction = { type: 'LOG_IN'; user?: User } | { type: 'LOG_OUT' };
|
||||
|
||||
export const INITIAL_AUTH_STATE: AuthState = {
|
||||
isAuthenticated: false,
|
||||
};
|
||||
Reference in New Issue
Block a user