Version: 0.0.1
Last Updated: Unknown
Use this tempalate to used to generate a basic context hook that throws errors without providers being used.
| Variable | Data Type | Info |
|---|---|---|
name | string | Context provider name |
1import * as React from "react";23interface <%= _.upperFirst(_.camelCase(name)) %>Props {4 count: number;5}67type <%= _.upperFirst(_.camelCase(name)) %>Tuple = (8 | <%= _.upperFirst(_.camelCase(name)) %>Props9 | React.Dispatch<React.SetStateAction<<%= _.upperFirst(_.camelCase(name)) %>Props>>10)[];1112const <%= _.upperFirst(_.camelCase(name)) %>Context = React.createContext<<%= _.upperFirst(_.camelCase(name)) %>Tuple | undefined>(13 undefined14);1516interface <%= _.upperFirst(_.camelCase(name)) %>ProviderProps {17 initialState: <%= _.upperFirst(_.camelCase(name)) %>Props;18 children: React.ReactChildren;19}2021/**22 * @param props Props to pass to provider23 * @param props.initialState Initial state for context24 * @returns {React.ReactElement} Context Provider25 */26export const <%= _.upperFirst(_.camelCase(name)) %>Provider: React.FC<<%= _.upperFirst(_.camelCase(name)) %>ProviderProps> = ({27 initialState,28 ...props29}) => {30 const [testingValue, set<%= _.upperFirst(_.camelCase(name)) %>] = React.useState(initialState);31 const value = [testingValue, set<%= _.upperFirst(_.camelCase(name)) %>];3233 return <<%= _.upperFirst(_.camelCase(name)) %>Context.Provider value={value} {...props} />;34};3536/**37 * Hook to access state38 *39 * @returns {<%= _.upperFirst(_.camelCase(name)) %>Tuple} hook to access state and dispatch40 */41export const use<%= _.upperFirst(_.camelCase(name)) %> = () => {42 const context = React.useContext(<%= _.upperFirst(_.camelCase(name)) %>Context);43 if (!context) {44 throw new Error(45 `use<%= _.upperFirst(_.camelCase(name)) %> must be rendered within the <%= _.upperFirst(_.camelCase(name)) %>Provider`46 );47 }48 return context;49};