I’m working on a React project using React Query and ts-rest. I need some assistance with conditionally enabling a query based on the length of the search term. Specifically, I want the query to be enabled only if the search term has at least 5 characters or if the search term is empty.
const [query, setQuery] = useState<{ searchTerm: string; offset: number }>({
searchTerm: '',
offset: 0,
});
const { data, refetch } = client.medication.getMany.useQuery(['medication'], {
query: {
...query,
limit,
},
// enabled: query.searchTerm?.length >= 5 || !query.searchTerm, <- something like this
});
I’m not sure how to properly implement the enabled parameter to achieve this functionality. Could someone guide me on how to do this?
I’ve tried to do it with a useEffect but i was wondering if there are other methods.
useEffect(() => {
if (
query.searchTerm?.length >= 5 ||
!query.searchTerm ||
query.offset !== 0
) {
refetch();
}
}, [query.searchTerm, limit, query.offset]);
tvh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.