more
This commit is contained in:
48
frontend/src/contexts/UserPropertiesContext.jsx
Normal file
48
frontend/src/contexts/UserPropertiesContext.jsx
Normal 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>
|
||||
);
|
||||
}
|
||||
20
frontend/src/contexts/userPropertiesReducer.js
Normal file
20
frontend/src/contexts/userPropertiesReducer.js
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user