T
TanStack2y ago
rival-black

Is enriching the query-return props a good practice?

Hey 👋🏽 , I'm interested in your opinion. Please check out following code:
// use-current-user.js
export function useCurrentUser() {
const query = useQuery({
queryKey: ["users", "detail", "me"],
staleTime: 1000 * 1800,
queryFn: () => rq(currentUserQuery).then((data) => data.currentUser),
});

return {
...query,
currentUser: query.data,
hasRightFn: (right) =>
query.isSuccess ? query.data.rights.includes(right) : false,
};
}
// use-current-user.js
export function useCurrentUser() {
const query = useQuery({
queryKey: ["users", "detail", "me"],
staleTime: 1000 * 1800,
queryFn: () => rq(currentUserQuery).then((data) => data.currentUser),
});

return {
...query,
currentUser: query.data,
hasRightFn: (right) =>
query.isSuccess ? query.data.rights.includes(right) : false,
};
}
function MyComponent() {
const { hasRightFn } = useCurrentUser();

return (
<div>
{hasRightFn("refund_allowed") ? (
<Button>Refund</Button>
) : null}
</div>
)
}
function MyComponent() {
const { hasRightFn } = useCurrentUser();

return (
<div>
{hasRightFn("refund_allowed") ? (
<Button>Refund</Button>
) : null}
</div>
)
}
Here the return properties are enriched by 2 further properties (hasRightFn and currentUser). Are there any disadvantages here? I think no. thanks
2 Replies
sensitive-blue
sensitive-blue2y ago
...query spreading is a bit troublesome with tracked queries. we have a lint rule that warns you about this. if possible, do:
return {
query,
currentUser,
hasRightFn
}
return {
query,
currentUser,
hasRightFn
}
rival-black
rival-blackOP2y ago
Thanks for the tip! That is of course not a problem.

Did you find this page helpful?