In my React application with TypeScript, I want to create a context for a component. The createContext shows an error when a default value is not provided. One of the values I want to pass is the setFilters which is a hook dispatcher. How should I provide a default value?
Also, I do not want it optional, to prevent ! from invocation.
export interface ContextProps {
filters: FiltersType;
setFilters: React.Dispatch<React.SetStateAction<FiltersType>>;
}
export const MyContext = React.createContext<ContextProps>({
filters: defaultFilters, // imported from constants holder
setFilters: // <---- What should be here?
});
const FiltersContext: React.FC<IProps> = (props: IProps) => {
const [filters, setFilters] = React.useState<FiltersType>(defaultFilters);
return <MyContext.Provider value={{ filters, setFilters }}>{props.children}</MyContext.Provider>;
};
export default FiltersContext;
The default value is used when no context provider is available, so it depends what do you want to do in such situation. You can throw an error, then use setFilters: () => { throw new Error('No FiltersContext available'); }, or silently ignore it, then setFilters: () => {} would do, or whatever you want to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With