Context hooks
useKelpClient, useKelpIdentity, useKelpAnalytics, useKelpQuery, and useDebouncedValue - the lower-level hooks exported from @kelpclick/client/react.
In addition to useSearch and useBrowse, the @kelpclick/client/react entry exports five lower-level hooks.
All hooks that read from context throw if called outside a <KelpProvider>.
useKelpClient
Returns the KelpClient instance from context.
function useKelpClient(): KelpClientUse it when you need to call client.search or client.browse directly, or access any other method on the client:
import { useKelpClient } from '@kelpclick/client/react';
function ManualSearch() {
const client = useKelpClient();
async function runQuery() {
const res = await client.search<Product>('products', { q: 'shirt' });
console.log(res.hits);
}
return <button onClick={runQuery}>Search</button>;
}useKelpIdentity
Returns the KelpIdentity instance from context.
function useKelpIdentity(): KelpIdentityUse it to read or set identity information (session id, anonymous id, known user):
import { useKelpIdentity } from '@kelpclick/client/react';
function LoginHandler({ userId }: { userId: string }) {
const identity = useKelpIdentity();
function onLogin() {
identity.identify({ userId, email: 'user@example.com' });
}
return <button onClick={onLogin}>Log in</button>;
}The KelpIdentity interface:
interface KelpIdentity {
getAnonymousId(): string;
getSessionId(): string;
getUserId(): string | null;
identify(fields: { userId?: string; email?: string }): void;
reset(): void;
}See Identity for full documentation.
useKelpAnalytics
Returns the analytics tracker from context. Use it to emit events from anywhere in the tree without threading props.
function useKelpAnalytics(): KelpAnalyticsimport { useKelpAnalytics } from '@kelpclick/client/react';
function AddToCartButton({ productId, queryId }: { productId: string; queryId?: string }) {
const analytics = useKelpAnalytics();
function handleClick() {
analytics.trackProductAddedToCart({
collection: 'products',
objectId: productId,
queryId,
});
}
return <button onClick={handleClick}>Add to cart</button>;
}The tracker exposes the full KelpAnalytics surface - trackSearch, trackProductViewed, trackProductClicked, trackProductWishlisted, trackProductAddedToCart, trackCollectionViewed, trackPurchase, startSession, trackSessionStarted, track, and flush. track() accepts a named KelpEventKind only. See Events for the closed kind list.
useKelpQuery
The low-level query hook that powers useSearch and useBrowse. Use it when you need a custom runner - for example, to call a different endpoint or apply server-side transforms - while keeping the pagination, filter, and status machinery.
function useKelpQuery<TDoc = KelpDocumentBase>(opts: UseKelpQueryOptions<TDoc>): UseKelpQueryResult<TDoc>Options
interface UseKelpQueryOptions<TDoc> {
/** Called on each fetch. Must return a KelpSearchResponse. */
runner: (args: KelpQueryRunnerArgs) => Promise<KelpSearchResponse<TDoc>>;
perPage?: number;
initialPage?: number;
initialFilters?: KelpFilters;
/** Set false to skip fetching (e.g. a disabled search box). Default true. */
enabled?: boolean;
/** Extra deps that retrigger the query (e.g. the debounced query string). */
deps?: unknown[];
/** Fired once per successful fetch. */
onSuccess?: (res: KelpSearchResponse<TDoc>, args: KelpQueryRunnerArgs) => void;
}The runner receives:
interface KelpQueryRunnerArgs {
page: number;
perPage: number;
filters: KelpFilters;
signal: AbortSignal;
}Pass the signal to your fetch call so in-flight requests are cancelled when a new one starts.
Return value
Same as the non-query-specific portion of useSearch/useBrowse:
{
page, setPage, perPage, setPerPage, totalPages,
hits, facetCounts, found, result,
filters, setFilters, toggleFilter, isFilterActive, clearFilters,
status, isLoading, error,
}Example
import { useKelpQuery, useKelpClient } from '@kelpclick/client/react';
import { useCallback } from 'react';
export function CustomSearchPage() {
const client = useKelpClient();
const debouncedQ = 'shirt'; // supply from useDebouncedValue in practice
const runner = useCallback(
({ page, perPage, filters, signal }) =>
client.search<Product>('products', { q: debouncedQ, page, perPage, filters }, { signal }),
[client, debouncedQ],
);
const { hits, isLoading, page, setPage, totalPages } = useKelpQuery<Product>({
runner,
perPage: 20,
deps: [debouncedQ],
});
// ...render
}useDebouncedValue
General-purpose debounce hook. Returns a value that only updates after delayMs milliseconds of silence.
function useDebouncedValue<T>(value: T, delayMs: number): TuseSearch uses this internally to debounce the query string before firing a request. You can use it for any value:
import { useDebouncedValue } from '@kelpclick/client/react';
import { useState } from 'react';
function FilterInput() {
const [input, setInput] = useState('');
const debounced = useDebouncedValue(input, 300);
// debounced updates 300 ms after the last keystroke
return <input value={input} onChange={(e) => setInput(e.target.value)} />;
}All context hooks (useKelpClient, useKelpIdentity, useKelpAnalytics) throw with the message "Kelp hooks must be used within a <KelpProvider>." if called outside a provider. This is a programming error, not a runtime condition - wrap the consuming subtree in <KelpProvider client={...}>.
Related
- KelpProvider - required wrapper for all hooks
- useSearch - full search hook
- useBrowse - collection browse hook
- Identity -
KelpIdentityfull reference - Analytics - event taxonomy and tracker API (link to analytics doc when available)