When I'm navigating between screens, react-query seems to struggle, as it ends up returning an undefined
.
To give a better perspective of the issue, here is how the issue is formed:
I have two routes at the moment:
Home and List
Inside Home
I have the following:
const lists = useQuery(["lists"], api.fetchLists);
...
{lists.isLoading && (
<React.Fragment>
<Skeleton />
</React.Fragment>
)}
...
{isEmpty()}
Inside isEmpty()
:
if (lists.data) {
return lists.data.lists.length ? (
{lists.data.lists?.map((list) => (
To navigate from home to List
, I use
navigate(`/list/${list.id}`)
Once I navigate to List
I do the following inside there:
const { listId } = useParams();
const list = useQuery(["lists"], () => api.fetchList(listId));
...
{list.isLoading ? (
<Card style={{ padding: 30 }}>
<div>
<Skeleton />
</div>
</Card>
) : (
{list.data}
)}
So, when I navigate to List
, the page goes blank. If I reload, everything loads normally. After a reload, if I try to go to Home
, then Home
goes blank and says Cannot read properties of undefined (reading 'length')
Why is this happening, and how can I fix this issue?
CodePudding user response:
You are using the same query key for fetching "all lists" and "a single list", so the caches are overriding each other. As a rule of thumb, always put all dependencies of the query function into the query key:
const { listId } = useParams();
const list = useQuery(["lists", listId], () => api.fetchList(listId));
if listId
is potentially undefined
on the first render, disable the query as long as it's not defined:
const { listId } = useParams();
const list = useQuery(
["lists", listId],
() => api.fetchList(listId),
{ enabled: !!listId }
)