useQuery Hook
Basic Setup & Configuration
1. How do I import the useQuery hook?
You can import the useQuery hook from @unbxd-ui/react-search-hooks
:
import { useQuery } from "@unbxd-ui/react-search-hooks";
UnbxdSearchCSRWrapper
or UnbxdSearchSSRWrapper
components.2. Can I delay/debouncing API calls in useQuery?
The useQuery hook uses debouncing to delay API calls and improve performance. You can control the debounce delay. The setQuery function is debounced, so rapid typing won't trigger multiple API calls. Click here to view the details on delay.
3. Can I force a query update even if the value hasn't changed?
Yes, use the forceReload
option to trigger updates regardless of whether the query value has changed. Click here to view the details on forceReload.
This is useful for refresh functionality or when you need to re-execute the same search.
4. How does the suggestedQuery feature work?
The useQuery hook provides query suggestions from two sources:
const { query, suggestedQuery } = useQuery();
// suggestedQuery can come from:
// 1. "Did You Mean" suggestions (didYouMean[0].suggestion)
// 2. Fallback suggestions (fallback.q)
if (suggestedQuery) {
console.log(`Did you mean: ${suggestedQuery}?`);
}
The hook prioritizes "Did You Mean" suggestions over fallback suggestions.
Behavior
1. How can I know if a query has been set?
You can determine if a query has been set by checking the productType
from the store. When a query is executed, the productType
is automatically set to SEARCH
.
Events & callbacks
1. What events does useQuery dispatch?
The useQuery hook dispatches two types of events:
// QUERY_UPDATED event when query changes
setQuery("new query"); // Dispatches: { type: QUERY_UPDATED, message: "Query updated", value: "new query" }
// ERROR event when errors occur
onError("SearchBox", "Invalid query format"); // Dispatches: { type: ERROR, message: "SearchBox: Invalid query format" }
These events can be used for analytics, logging, or custom error handling.
2. How does useQuery handle default query values?
The useQuery hook uses default query values from the configuration when setting empty queries:
// If newQuery is empty, it falls back to defaultQuery from configs
setQuery(""); // Will use defaultValues.query if configured
// In your wrapper configuration:
<UnbxdSearchCSRwrapper
defaultValues={{
query: "default search term",
}}>
<MySearchComponent />
</UnbxdSearchCSRwrapper>;