T
TanStack2y ago
extended-salmon

Use `select` or return from inside query function?

We have an API that returns { metadata: Record<string, CustomType> }. Often times we only want one of the returned CustomType. The Record is of IDs to CustomType so when we pass in one ID, we only want one returned. Should we be using the select function to return that one object or can we return it right inside the query function? Using select:
const { data } = useQuery([queryKeys, objectID],
async () => {
const response = await APIRequest(objectID);
return response.data
},
{
enabled: !!objectID,
select(data) => {
return data?.metadata?.[objectID]
}
}
)
const { data } = useQuery([queryKeys, objectID],
async () => {
const response = await APIRequest(objectID);
return response.data
},
{
enabled: !!objectID,
select(data) => {
return data?.metadata?.[objectID]
}
}
)
or purely in the query function:
const { data } = useQuery([queryKeys, objectID],
async () => {
const response = await APIRequest(objectID);
return response.data?.metadata?.[objectID]
},
{
enabled: !!objectID,
}
)
const { data } = useQuery([queryKeys, objectID],
async () => {
const response = await APIRequest(objectID);
return response.data?.metadata?.[objectID]
},
{
enabled: !!objectID,
}
)
I thought I saw something that we needed to always return response.data so useQuery could properly handle everything but now I'm not so sure. We are sadly on v3 of react-query still...
2 Replies
extended-salmon
extended-salmon2y ago
select sounds good for that 👍
extended-salmon
extended-salmonOP2y ago
awesome thank you!

Did you find this page helpful?