1

I have the following code:

  const queryInput = useRef()
  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    if (queryInput && queryInput.current) {
      console.log(`queryInput.current.value`, queryInput?.current?.value ?? null)
    }
  }
  return (
...

And I'm getting the following error in vscode:

(property) MutableRefObject<undefined>.current: undefined
Object is possibly 'undefined'.ts(2532)

Even though I tried to avoid it with the if clause and the optional chaining operator.

From the console I get the same error:

$ npx tsc
pages/_app.tsx:14:47 - error TS2532: Object is possibly 'undefined'.

14       console.log(`queryInput.current.value`, queryInput?.current?.value ?? null)
                                                 ~~~~~~~~~~~~~~~~~~~


Found 1 error.

Also checked this SO answer: How can I solve the error 'TS2532: Object is possibly 'undefined'?

and this blog post: https://linguinecode.com/post/how-to-solve-typescript-possibly-undefined-value

but I can't seem to solve the issue

BTW, this is my ts version:

  "devDependencies": {
    "@types/node": "^14.14.31",
    "@types/react": "^17.0.2",
    "typescript": "^4.2.2"
opensas
  • 60,462
  • 79
  • 252
  • 386
  • 1
    Try to pass `null` to your `useRef` hook - `useRef(null);` and see if that helps anything. – mtbno Mar 04 '21 at 13:19

1 Answers1

3

The problem was fixed by passing initial value of null to the useRef hook:

const queryInput = useRef(null);
mtbno
  • 561
  • 7
  • 12