React-Query generally returns some query states such as isLoading, isError. The library guarantees that these booleans are stable. This means we can be sure that the data is present if e. g. check for the onSuccess boolean. However, this - of course - isn't enough for the TS compiler. Even after the check, it assumes that the data can be undefined. What's the best way to let the TS compiler know that the data is present?
Here's an example from the docs:
function Todos() {
const { isLoading, isError, data, error } = useQuery('todos', fetchTodoList)
if (isLoading) {
return <span>Loading...</span>
}
if (isError) {
return <span>Error: {error.message}</span>
}
// --> The data is now sure to exist
return (
<ul>
{data.map(todo => ( // --> this will not work with the TS compiler.
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}