skip to Main Content

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


  1. You should try to use try catch block in MyComponent function, where it will catch the uncaught error, refer this:

     function MyComponent() {
      try {
        const object = useGetComplexObject()
        return (
          <div>
            <p>current object : {object.kind}</p>
          </div>
        )
      } catch (error) {
        return (
          <div>
            <p>Error: {error.message}</p>
          </div>
        )
      }
    }
    

    It will give you specific error you are occurring.
    Hope this solves your problem.

    Login or Signup to reply.
  2. Change your useGetComplexObject code like bellow.

    const useGetComplexObject = () => {
      try {
        const object = useContext(Context)
        return object
      } catch (error: any) {
          throw new Error("useGetComplexObject must be used within the parameter");
      }
    }

    hope this will help to fix your code error.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search