T
TanStack3y ago
fair-rose

How is the best way to handle this with deconstructing and Select?

export default function useAuth() {
return useQuery({
queryKey: ['auth'],
queryFn: async () => {
const response = await fetch(`url`);
return response.json();
},
refetchInterval: 300000,
select: (data) => {
return {
user: data,
};
},
});
}
export default function useAuth() {
return useQuery({
queryKey: ['auth'],
queryFn: async () => {
const response = await fetch(`url`);
return response.json();
},
refetchInterval: 300000,
select: (data) => {
return {
user: data,
};
},
});
}
and within the component I want to do
const { data } = useAuth()
const { user } = data
const { data } = useAuth()
const { user } = data
but I get the error that user doesnt exist because data is undefined
2 Replies
rival-black
rival-black3y ago
Hi. Yes this is the normal behaviour : while loading for ex, the data of the query are undefined. You could either use placeholderdata/initialdata in the query. Or set a default value while destructuring. More info could be found here: https://tkdodo.eu/blog/placeholder-and-initial-data-in-react-query
quickest-silver
quickest-silver3y ago
no you can't because as glabat mentioned, data will be undefined in some cases, most notably while loading

Did you find this page helpful?