The key was to use Dependent Queries
So, in my main component, I create a boolean and pass that to the enabled
option of the useQuery
hook:
const isLongEnough = searchString.length > 3;
const {data, isLoading} = useQuery(['search', searchString], getSearchResults, {enabled: isLongEnough});
and the API calling method is simply the API call – not any conditional:
const getSearchResults = async (_, searchString) => {
const {data} = await axios.get(`/search?q=${searchString}`);
return data;
}
The docs describe dependent queries as a solution for loading data from subsequent API endpoints, but the enable
option can accept any boolean. In this case – if the search query string is long enough.