query
query copied to clipboard
Quick Start example fails with "query.data is undefined"
Describe the bug
Totally new to React Query.
In a fresh React 16 app, created with create-react-app
I followed the "Quick Start" - https://react-query.tanstack.com/quick-start
It imports getTodos
and postTodo
without providing implementations. Fine - although this could do with some explanation in the docs. I wrote some dummy query functions, just to get something to play with.
The app fails to render because - I discovered, after reading https://www.neldeles.com/blog/posts/handling-undefined-in-react-query - on first render cycle, the data does not exist yet.
The Quick Start code doesn't handle this. Instead it throws Uncaught TypeError: query.data is undefined
Your minimal, reproducible example
see "steps to reproduce"
Steps to reproduce
let todos = [{ id: new Date(), title: "foo" }];
const getTodos = function () {
return todos;
};
const postTodo = async (todo) => {
todos.push(todo);
return todos;
};
Expected behavior
As a user I expected to see a working page. Instead I had to edit the code provided by the quick start example. The following works (crucially, I have had to handle .isLoading
and .isError
)
function Todos() {
// Access the client
const queryClient = useQueryClient();
// Queries
const query = useQuery("todos", getTodos);
// Mutations
const mutation = useMutation(postTodo, {
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries("todos");
},
});
if (query.isLoading) {
return <span>Loading...</span>;
}
if (query.isError) {
return <span>Error: {query.error.message}</span>;
}
return (
<div>
<ul>
{query.data.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
<button
onClick={() => {
mutation.mutate({
id: Date.now(),
title: "Do Laundry",
});
}}
>
Add Todo
</button>
</div>
);
}
How often does this bug happen?
No response
Screenshots or Videos
No response
Platform
macOS Firefox
react-query version
v3.34.19
TypeScript version
No response
Additional context
No response
would you like to contribute a fix? could also just be:
- query.data.map
+ query.data?.map
we're going into loading / error states a lot in the other parts of the docs
Sure, yes, I'd like to try and submit a pull request.
How about I include:
- enough imports for the whole thing to work as
index.js
in a freshly-created app usingcreate-react-app
- basic, inline implementations of
getTodos
andpostTodo
, with comments explaining that they should talk to a server, for a real implementation?
Then, newcomers would be able to inspect and use a working example by just copying and pasting into index.js
. I think this would improve the learning curve and would only be a few lines of code different from what's already there
fixed with: c08c0a1cd304a7e42e792d1d91fb3da7a84b4704