Instructor: Our fetch Ricks function is set to only look for the name of Rick inside of our endpoint. That means, when we refresh, it's going to immediately fire the query and look for any character with the name of Rick. Thankfully, React Query lets us use dependent queries so we can actually hold off on firing that query and wait until we have a user input from a search bar.
First let's declare some state so we can track our input. Let's do another state so we can put that input into a variable to send to our query. Let's set up an input and a button to interact with.
Let's attach an on change to our input where we take the event and send it into our set input with the event.target.value.
Then we'll tack an on click onto our button so we can get that value into our input and send that into set name. Let's head back to our current use query where we have a query key of characters. Earlier we talked about how we can turn the query key into an array. Or we can send a variable into our fetch Ricks function that is name.
Fetch Ricks function has the option available to it through its arguments. They are in the same order they are in the array, so we'll get the string which we're not going to use and the argument, which is the name.
We'll remove the current quotations and replace them with template strings, take out the Rick, and insert our arg. Not the name, but the arg so that when we pass through the argument it'll go into the API.
When we refresh there's going to be an error because currently the query is firing with an undefined name. If we check to make sure name is not undefined or falsy, you'll see that when we refresh there's a search bar with no error.
Now we can try searching Rick. As you can see, our name is now being sent into our API. We can search Morty and we can also search Beth or any other name in the universe.
Now let's check out some examples from the docs so we can see the different ways we can use dependent queries inside of our apps. Our first option is to pass a falsy query key. As you can see here, first we'll get the user, then we'll get the user's projects. But in the query key we'll double check to make sure the user isn't falsy before trying to grab the user.id.
Our next option is to pass a query key with a falsy item. First we'll check to make sure email is available before checking for the user. Then we'll get the user's projects. Inside the query key array, we'll double check to make sure user isn't falsy before grabbing the user ID inside the array. A third option is to use a query key function which is just an anonymous function that won't run until user.id is available.
Let's go back down to our query where you can see we're actually using the passing falsy query key option to make our dependent query work.