Home > Net >  react createContext not working with typescript
react createContext not working with typescript

Time:02-18

I'm trying to implement the following toast manager to my react typescript application

enter image description here

CodePudding user response:

The error message says that it is a "TypeError" but actually this is not related to typescript. That is a JavaScript error which occurs if you try to invoke something that isn't actually a function. For example, null is not a function and would throw this error if you tried to invoke it.

The error is most likely that you are not rendering your ToastTest component inside of your ToastContextProvider component. Your call to useToast is probably getting the default value of "null" and throwing this error when it tries to call "null" as a function. Make sure that your ToastContextProvider is a parent or grandparent to your ToastTest component.

CodePudding user response:

It's a Typescript error on <ToastContext.Provider value={addToast}>. The value in the Provider can only receive null because we passed null to createContext.

Declare null as any:

const ToastContext = createContext(null as any);
  • Related