This commit is contained in:
KS Jannette
2026-03-29 00:02:38 -04:00
parent 33ec729631
commit 3a52e7afb3
5 changed files with 86 additions and 13 deletions

View File

@@ -0,0 +1,48 @@
import { createContext, useContext, useReducer, useEffect } from "react";
import {
userPropertiesReducer,
initialState,
ACTION_TYPES,
} from "./userPropertiesReducer";
const STORAGE_KEY = "kp_onboard_user";
function hydrateState() {
try {
const raw = sessionStorage.getItem(STORAGE_KEY);
if (raw) return { ...initialState, ...JSON.parse(raw) };
} catch {
/* corrupt data — fall through */
}
return initialState;
}
const UserPropertiesContext = createContext(initialState);
export function useUserProperties() {
const ctx = useContext(UserPropertiesContext);
if (!ctx) {
throw new Error(
"useUserProperties must be used within UserPropertiesProvider",
);
}
return ctx;
}
export function UserPropertiesProvider({ children }) {
const [state, dispatch] = useReducer(userPropertiesReducer, null, hydrateState);
useEffect(() => {
if (state.email || state.password) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(state));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
}, [state]);
return (
<UserPropertiesContext.Provider value={{ state, dispatch, ACTION_TYPES }}>
{children}
</UserPropertiesContext.Provider>
);
}

View File

@@ -0,0 +1,20 @@
export const initialState = {
email: "",
password: "",
};
export const ACTION_TYPES = {
SET_USER_PROPERTIES: "SET_USER_PROPERTIES",
CLEAR_USER_PROPERTIES: "CLEAR_USER_PROPERTIES",
};
export function userPropertiesReducer(state, action) {
switch (action.type) {
case ACTION_TYPES.SET_USER_PROPERTIES:
return { ...state, ...action.payload };
case ACTION_TYPES.CLEAR_USER_PROPERTIES:
return { ...initialState };
default:
return state;
}
}