T
TanStack15mo ago
national-gold

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>
}
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>
}
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>
<div>{data?.book?.name}</div>
(3) ?
1 Reply
harsh-harlequin
harsh-harlequin15mo ago
For data that is fetched once at the top of the tree and then you want to read it everywhere below, you can put the data in react-context (https://tkdodo.eu/blog/react-query-and-react-context). I personally prefer using useSuspenseQuery because it guarantees that data is defined, and it passes handling errors and loading states to boundary components that are further up in the tree

Did you find this page helpful?