Skip to content

Instantly share code, notes, and snippets.

@iamgauravbisht
Last active January 23, 2024 17:22
Show Gist options
  • Save iamgauravbisht/43a0737bd49e22dccae67d2908aec9fd to your computer and use it in GitHub Desktop.
Save iamgauravbisht/43a0737bd49e22dccae67d2908aec9fd to your computer and use it in GitHub Desktop.
Creating Store using Context API
import React, { createContext, useReducer } from "react";
type IState = {
loginEmail: string;
loginPassword: string;
};
const initialState: IState = {
loginEmail: "",
loginPassword: "",
};
// Define the context type
type MyContextType = {
state: IState;
dispatch: React.Dispatch<Action>;
};
export const MyContext = createContext<MyContextType | undefined>(undefined);
type Action =
| { type: "SET_LOGIN_EMAIL"; payload: IState["loginEmail"] }
| { type: "SET_LOGIN_PASSWORD"; payload: IState["loginPassword"] }
;
function reducer(state: typeof initialState, action: Action) {
switch (action.type) {
case "SET_LOGIN_EMAIL":
return { ...state, loginEmail: action.payload };
case "SET_LOGIN_PASSWORD":
return { ...state, loginPassword: action.payload };
default:
return state;
}
}
//Provider
type Props = {
children: React.ReactNode;
};
export function MyProvider({ children }: Props): JSX.Element {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<MyContext.Provider value={{ state, dispatch }}>
{children}
</MyContext.Provider>
);
}
//useContext hook
import { useContext } from "react";
const useMyContext = () => {
const context = useContext(MyContext);
if (!context)
throw new Error(
"MyContext must be called from within the MyContextProvider"
);
return context;
};
export default useMyContext;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment