In my previous publications, I've explained the basics of React Query in my native language and now I'm gonna show an example of a live search with two concepts of React Query.
The environments on examples:
- Axios: 0.24.0
- React: 17.0.2
Scenario: There is an online application for tracking projects that companies have and for new project addition we need to search customers through the company's CRM and create a new project.
Live search on modal
This auto-completion form field should be filled with the customer names when the user types.
After every typing event whether we should complete all requests or only complete the last one. The First option can be useful when a user deletes a character on the word and search for a previous request but it can potentially trigger the server's rate limiting.
First Case:
const [value, setValue] = useState('');
const {
data: aaro,
isLoading,
error,
isFetching,
} = useQuery(
['aaroCari', value],
() =>
axios.get(
`${config.url.AARO_BASE}/api/Cari?EsnekAramaKisiti=${value}`,
{
headers,
}
),
{
enabled: Boolean(value),
}
);
As seen it retrieved the users when I wrote my name. And let's check react query dashboard for what happened.
Only the last one is active and the rest is inactive but if we take a look at the other request we see that they also retrieved the data.
This type of search can be useful in the situation when there is no server-side concern about requests. And it decreases the response time when the user deletes characters on the same word because we already have those options.
Second Case (Query Cancellation):
const [value, setValue] = useState('');
const {
data: aaro,
isLoading,
error,
isFetching,
} = useQuery(
['aaroCari', value],
({ signal }) =>
axios.get(
`${config.url.AARO_BASE}/api/Cari?EsnekAramaKisiti=${value}`,
{
headers,
signal,
}
),
{ enabled: Boolean(value) }
);
In that scenario, we put a {signal}
parameter on Axios and canceled all the previous requests.
As seen the previous values are empty now. By doing that we saved unnecessary requests from the server.
Exploring Server Side
For both scenarios, let's check the server's responses. I'll write the long text "lorem ipsum dolor sit amet" on the search bar and watch the responses.
Server Responses on Scenario 1:
As seen it returns a response for every character and the first lorem part are bigger packages because they match with some customers.
Server Responses on Scenario 2:
For the second request type, the server takes requests as well but they are canceled and it only responses for the last request.
Before finishing the writing, I should mention that { enabled: Boolean(value) }
option added both cases for preventing empty requests.
Thank you for reading.