T
TanStack3y ago
fair-rose

switching between endpoints in react query

Say that i have 2 endpoints one of which displays users and the other displays admins.I will have 2 buttons that call users or admins when clicked.For this i need to switch between the endpoints.how can i do thag
11 Replies
equal-aqua
equal-aqua3y ago
IMHO this should not be handled with react query. Just have two queries and access the desired one
fair-rose
fair-roseOP3y ago
If i make 2 queries and specify conditions and then display them in react,it would be a mess if i have too many queries.instead i want to have a single query and i want its content to be a certain thing based on the condition i specified
equal-aqua
equal-aqua3y ago
Okay. Then go ahead and write a custom wrapper hook that alters queryFn based on a parameter. No problem. But make sure to use that parameter as part of queryKey
fair-rose
fair-roseOP3y ago
I actually did something similar to this.it seemly worked but there was one issue: Everytime qhen i access a query with a specific key for the first time it sent me to the top of the page(refreshing) but on subsequent interactions it stopped doing it.so this is why i thought that it does it because it is the first time react query sees that key The click wasnt a form click btw
//API CALLS
const apiEndpoints = {
posts:fetchUserPostsByLike,
showcases:fetchUserPostsByDate,
pinned:fetchUserPostsByLike
}

const { id } = useParams(); // it always gets it as a string even if it is a number
const postsData =
useQuery(["post", activePosts],
async () => {
return await apiEndpoints[activePosts](id);
});
//API CALLS
const apiEndpoints = {
posts:fetchUserPostsByLike,
showcases:fetchUserPostsByDate,
pinned:fetchUserPostsByLike
}

const { id } = useParams(); // it always gets it as a string even if it is a number
const postsData =
useQuery(["post", activePosts],
async () => {
return await apiEndpoints[activePosts](id);
});
activePosts here is the useState that changes based on user interactions when user changes that state to become posts, postsData changes as well But the thing is that it refreshes everytime it sees a key for the first time and i dont want that the properties in apiEndpoints are api calls i get from a different file
equal-aqua
equal-aqua3y ago
What do you want instead?
fair-rose
fair-roseOP3y ago
that it wont refresh like it does in subsequent requests
equal-aqua
equal-aqua3y ago
The keep previous data flag might be what you’re looking for
fair-rose
fair-roseOP3y ago
will check it out
equal-aqua
equal-aqua3y ago
keepPreviousData: boolean
fair-rose
fair-roseOP3y ago
bro, thanks a ton.i did keepPreviousData:true and it worked.i have been trying to figure it out for 2 days and you are my saver!
equal-aqua
equal-aqua3y ago
You’re welcome

Did you find this page helpful?