React

Context API

Description:

SARASA

1. Context API implementation

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 // Create the data type of the context. type DataType = { name: string; lastName: string; }; // Create the context. const ContextApiData = createContext<DataType | undefined>({name: "Ale", lastName: "Polak"}); // Create the provider. /** * This provider is going to be Higher Order component that is going to wrap whatever component we pass * as a children and is going to give it the ability to access the Context Data from the custom hook. */ interface ContextApiProviderPropType { children: React.ReactElement; } export const ContextApiProvider = ({children}: ContextApiProviderPropType) => { const [data, setData] = useState<DataType>(); useEffect(() => { setData({name: "Jake", lastName: "Peralta"}) }, []); return( <ContextApiData.Provider value={data}> {children} </ContextApiData.Provider> ); }; // Create the hook to access it. export const useContextApiData = () => { const context = useContext(ContextApiData); if(!context) { throw Error("The useContextApiData should be use inside a provider."); } return context; };
๐Ÿ›๏ธ ๐Ÿงฎ ๐Ÿ“ โš›๏ธ ๐Ÿงช ๐Ÿ