I wrote a program in react typescript, but I got an error called uncaught error and I did run and debug tests and searched on google, but I am unable to solve this error, so I need help from anyone who can solve this error. here is my program
react with typescript
import { createContext, useContext, useMemo, } from "react"
type ComplexObject = {
kind:string
}
const Context = createContext<ComplexObject | null >(null)
const useGetComplexObject=()=>{
const object=useContext(Context)
if(!object)
{
throw new Error("useGetComplexObject must be used within the parameter");
return object
}
}
export default function MyApp()
{
const object =useMemo(()=>({kind:"complex"}),[])
return (
<Context.Provider value={object}>
<MyComponent />
</Context.Provider>
)
}
function MyComponent()
{
const object=useGetComplexObject()
return (
<div>
<p>current object : {object.kind}</p>
</div>
)
}
I searched this uncaught error on google but I cannot find solution for this error, what I am expecting is to anyone who knows react with typescript can help me to solve this uncaught TypeError and improve this program
2
Answers
You should try to use try catch block in MyComponent function, where it will catch the uncaught error, refer this:
It will give you specific error you are occurring.
Hope this solves your problem.
Change your useGetComplexObject code like bellow.
hope this will help to fix your code error.