Dependent queries in React Query

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.
Search for a command to run...

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.
No comments yet. Be the first to comment.
Most of you know me for my consistency, a golden arrow in my blog series. I've written 1000 articles in 1008 days! Almost an article a day, and my honeymoon was the only holiday I ever took. I'm super proud of this achievement; it has been a fantasti...

It's not the first time I'll be talking about community. I think it's an essential aspect of any successful tool. This shows in my previous explorations of Astro, Medusa, and now Vendure as well. All these products thrive in a super open, welcoming, ...

The cool part about Vendure is how easy it is to set up and how abstract each layer is. Basically, we get the following elements: External database Server Worker Admin UI Frontend While this is amazing, it also brings a bit of complexity when it co...

The previous article looked at customizing Vendure on a data and process level. In this article, we'll look at customizing emails, as they are often a big part of a webshop system. We'll be looking at two different layers of customization for customi...

Even though Vendure is a pretty significant project out of the box, in some cases, we might want to go in and modify some elements to work to our specific use case. In this article, I'll take a high-level look at some elements we can customize within...

In some cases, you might need only to fire a query once a specific condition is met.
Some examples of this:
And so on.
I'll show you how you can make this happen in React Query by using user input in this example.
You can see the result in the video below. We only start using the query once we have valid input. As long as it doesn't exist, we put the query into idle mode.

We can leverage the enabled property to make queries dependent on a variable.
This will tell React Query if this query should be enabled or not, and it can accept anything that calculates to a boolean.
You can use it like this:
const {isIdle, data} = useQuery('your-key', yourQueryFn, {
enabled: conditionIsTrue,
});
Let's try it out and create a user input. Only once this user input is more than zero should it be querying anything.
This code will be based on the React Query Pokemon app we built before.
The input will be placed in the App component.
function App() {
const [number, setNumber] = useState(0);
return (
<QueryClientProvider client={queryClient}>
<input
type="number"
value={number}
max="10220"
onChange={(e) => setNumber(e.target.value)}
/>
<button onClick={() => setNumber(0)}>reset</button>
<PokemonList number={number} />
</QueryClientProvider>
);
}
We keep track of a state number, and we update the state on change.
This state gets passed to our PokemonList component.
Let's look at how the PokemonList component can receive this number and how we can make our query dependent on it.
function PokemonList({number}) {
const {isIdle, data, isLoading} = useQuery(
['pokemon', number],
() => fetchPokemon({number}),
{
enabled: number > 0,
}
);
return <></>;
}
We receive the number and assign it to a specific unique key, as you can see above.
Then we invoke the fetchPokemon function and pass along the number to this function.
The dependency comes in at the enabled property where we tell react query only to enable this once it's bigger than zero.
Let's take a look at how our fetchPokemon function looks like now:
const fetchPokemon = async ({number}) => {
const request = await fetch(`https://pokeapi.co/api/v2/pokemon/${number}`);
return await request.json();
};
And then all that's left is to fix the actual return in the component.
We'll add some data for this Pokemon and keep track of our isIdle and isLoading states, so the user knows what's going on.
function PokemonList({number}) {
const {isIdle, data, isLoading} = useQuery(
['pokemon', number],
() => fetchPokemon({number}),
{
enabled: number > 0,
}
);
return (
<div className="App">
{isIdle ? (
<p>Is idle...</p>
) : isLoading ? (
<p>Loading...</p>
) : (
<ul>
<li>
<strong>Name</strong>: {data.name}
</li>
<li>
<strong>Weight</strong>: {data.weight}
</li>
<li>
<strong>Image</strong>:
</li>
<li>
<img
src={data.sprites?.front_shiny ?? data.sprites?.front_default}
alt={data.name}
/>
</li>
</ul>
)}
</div>
);
}
And that's it! We made our first dependent react query function.
You can try it out in this Code Sandbox:
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter