Open utterances-bot opened 3 years ago
Thanks for the great article. It's definitely clarified many things. The only thing that's not explained:
if you define dispatch as not mandatory
export interface Store {
state: StateContext;
dispatch?: React.Dispatch<Action>;
}
then in a view we get the TypeScript error:
Cannot invoke an object which is possibly 'undefined'.ts(2722)
If I remove the ? sign, making it necessary to specify I'm not sure what I should place in the createContext initializer
@sashker I'm glad it has helped you. If you make dispatch mandatory, you could just give the dispatch property in createContext
a null value.
export interface Store {
state: StateContext;
dispatch: React.Dispatch<Action>;
}
const myContext = React.createContext<Store>({ state: defaultState, dispatch: null });
Hi @nainarazz, first, thanks for this article, helped a lot.
I'm having the same issue that @sashker mentioned, change it to be mandatory as you suggest but still having an error:
Cannot invoke an object which is possibly 'null'. TS2721
Any suggestion to get out of this cycle?
Thanks
How to create global state using React hooks in TypeScript | Naina Codes
In this post, I will show you how to create a global state management without using a third party library like Redux. Why do we need a…
https://www.nainacodes.com/blog/global-state-using-react-hooks