How to assert NonNullable data on UseQuery
I have a custom hook with infinite query. I check for undefined at the app first render and then it is reused so I know by then, the type should not be undefined. I would like to be able to infer its type without undefined conditionally. Can I do that? How to if so??
the type of data will be in this case always the TYPE | undefined.
const { data } = useAppContext()
I would like it to be:
1st time (app top level) of type -> TYPE | undefined
and then force it to be just -> TYPE so I dont have to do checking for undefined or mark chaining of data property with ! as I know at this time it's already in the cache and exists1 Reply
afraid-scarlet•3y ago
the thing is, you can't be sure that data is there. It can be garbage collected, or a query can fail. Sure, you can say you only render a component after you've checked it at the parent level, but at this point, you're building an implicit dependency between the child and the parent. A small refactoring, where you move the component to another sub-tree where data has not been fetched yet might lead to breakage because it's not clear that this component depends on data from the parent.
It's better to either make this dependency explicit (by prop-drilling or using react context) or make the component independent (by calling useQuery and guarding against data not being there)