TanStackT
TanStack2y ago
1 reply
faint-white

React query in typescript strict mode

Hi everyone,

I am working in a company where we recently updated typescript in strict mode, so it means the strictNullCheck value will be activated.

So now, if I am writing code like this, typescript will raise an error:
const Comp = () => {
  const { data } = useMyQuery()

  // 'data.book.name' is possibly 'undefined'. ts(18048)
  return <div>{data.book.name}</div>
}


The fix:
const Comp = () => {
  const { data, isSuccess } = useMyQuery()

  if(!isSuccess) {
    return null; // or return error component
  }

  return <div>{data.book.name}</div>
}


Now, I have data that is fetched once at the top of the tree when the app initialize, it returns some global permissions configuration for the logged user.
However this hook is used in several nested sub-component of the app preventing props-drill.

My question is related to react-query best practices:

(1) Should we handle errors on all nested components ?
- It makes the component typesafe and resilient to potential refactor issues
- It adds lots of boilerplate and redundant code

(2) Should we use optional chaining everywhere
- Not a huge fan of this, because in case of errors it can fail silently, Plus it is noisy and not typesafe
<div>{data?.book?.name}</div>


(3) ?
Was this page helpful?