Last active
January 23, 2024 17:22
-
-
Save iamgauravbisht/43a0737bd49e22dccae67d2908aec9fd to your computer and use it in GitHub Desktop.
Creating Store using Context API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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