39 lines
1001 B
JavaScript
39 lines
1001 B
JavaScript
// UserProfileContext.js
|
|
import { createContext, useContext, useReducer } from "react";
|
|
|
|
// Define the initial state
|
|
const initialState = {
|
|
userProfile: null,
|
|
};
|
|
|
|
// Create the context
|
|
const UserProfileContext = createContext();
|
|
|
|
// Create a custom hook for using the context
|
|
export const useUserProfile = () => {
|
|
return useContext(UserProfileContext);
|
|
};
|
|
|
|
// Define a reducer function to update the context state
|
|
const userProfileReducer = (state, action) => {
|
|
switch (action.type) {
|
|
case "SET_USER_PROFILE":
|
|
return { ...state, userProfile: action.payload };
|
|
case "CLEAR_USER_PROFILE":
|
|
return { ...state, userProfile: null };
|
|
default:
|
|
return state;
|
|
}
|
|
};
|
|
|
|
// Create the UserProfileProvider component
|
|
export const UserProfileProvider = ({ children }) => {
|
|
const [state, dispatch] = useReducer(userProfileReducer, initialState);
|
|
|
|
return (
|
|
<UserProfileContext.Provider value={{ state, dispatch }}>
|
|
{children}
|
|
</UserProfileContext.Provider>
|
|
);
|
|
};
|