T
TanStack•3y ago
absent-sapphire

Best way to handle 2 queries (2 different endpoints) in a single view.

My view will have 2 different endpoints to call based on a call to action. I wanted to know what would be the best way to handle this? Would it be better to have something like (in the example I have used the placeholder api, but in my case it would be the same base url but different parameters e.g query1 endpoint: https://www.example.something/account and query2 endpoint: https://www.example.something/account/all/details. The way I have thought to do it is have a boolean state value and use that in the enabled flag of the query: stackblitz example - https://stackblitz.com/edit/react-ts-fbny3g?file=index.tsx Is there another way or better way to do this?
rS
StackBlitz
React query - Multiple queries in a single view - StackBlitz
React + TypeScript starter project
5 Replies
genetic-orange
genetic-orange•3y ago
Hi 👋 I think the best approach here is to conditionally render a component that unconditionally fetches and renders data, and conditionally render these components based on the state of the parent (the button events). You can remove a lot of the duplication here too should you want to with a custom hook that accepts the endpoint name as a parameter and uses it to form the query key.
absent-sapphire
absent-sapphireOP•3y ago
Hi Louis, So the endpoint would be different in terms of one endpoint would accept parameters while the other one would be just the stripped back endpoint. So I think that is what I want to do is remove the duplication in the example... can you expand on your approach?
genetic-orange
genetic-orange•3y ago
Sure. I'd suggest doing something like this:
const A = () => {
const query = useQuery(...);

return ...;
}

const B = () => {
const query = useQuery(...);

return ...;
}

const Parent = () => {
const [someState] = useState(false);

return someState ? <A/> : <B/>;
}
const A = () => {
const query = useQuery(...);

return ...;
}

const B = () => {
const query = useQuery(...);

return ...;
}

const Parent = () => {
const [someState] = useState(false);

return someState ? <A/> : <B/>;
}
Where A and B unconditionally perform the query and render data, and you conditionally render those components instead. This removes a lot of the complexity here in my opinion. How you want to handle hook/component reusability is up to you 🙂
absent-sapphire
absent-sapphireOP•3y ago
Thanks Louis, so your wrapping you're different queries into functions and then using a boolean flag to evaluate the condition, so are A, B different component files and then there is one parent file?
genetic-orange
genetic-orange•3y ago
Different components, yeah 🙂

Did you find this page helpful?