useSiteSearch is a Vue composable that you can use to render a DatoCMS Site Search widget.
The hook only handles the form logic: you are in complete and full control of how your form renders down to the very last component, class or style.
To perform the necessary API requests, this hook requires a DatoCMS CMA Client instance, so make sure to also add the following package to your project:
npm install --save vue-datocms @datocms/cma-client-browserImport useSiteSearch from vue-datocms and use it inside your components like this:
import { useSiteSearch } from 'vue-datocms';
import { buildClient } from '@datocms/cma-client-browser';
const client = buildClient({ apiToken: 'YOUR_API_TOKEN' });
const { state, error, data } = useSiteSearch({
client,
searchIndexId: '7497',
// optional: by default fuzzy-search is not active
fuzzySearch: true,
// optional: you can omit it you only have one locale, or you want to find results in every locale
initialState: { locale: 'en' },
// optional: defaults to 8 search results per page
resultsPerPage: 10,
});For a complete walk-through, please refer to the DatoCMS Site Search documentation.
| prop | type | required | description | default |
|---|---|---|---|---|
| client | CMA Client instance | ✅ | DatoCMS CMA Client instance | |
| searchIndexId | string | ✅ | The ID of the search index to use to find search results | |
| fuzzySearch | boolean | ❌ | Whether fuzzy-search is active or not. When active, it will also find strings that approximately match the query provided. | false |
| resultsPerPage | number | ❌ | The number of search results to show per page | 8 |
| initialState.query | string | ❌ | Initialize the form with a specific query | '' |
| initialState.locale | string | ❌ | Initialize the form starting from a specific page | 0 |
| initialState.page | string | ❌ | Initialize the form with a specific locale selected | null |
The hook returns an object with the following shape:
{
state: {
query: string;
locale: string | undefined;
page: number;
},
error?: string,
data?: {
pageResults: Array<{
id: string;
title: string;
titleHighlights: ResultHighlight[];
bodyExcerpt: string;
bodyHighlights: ResultHighlight[];
url: string;
raw: RawSearchResult;
}>;
totalResults: number;
totalPages: number;
},
}titleHighlights and bodyHighlights have the following shape:
type ResultHighlight = HighlightPiece[]
type HighlightPiece = {
text: string;
isMatch: boolean;
}- The
stateproperty reflects the current state of the form (the currentquery,page, andlocale), and offers a number of functions to change the state itself. As soon as the state of the form changes, a new API request is made to fetch the new search results; - The
errorproperty returns a string in case of failure of any API request; - The
dataproperty returns all the information regarding the current search results to present to the user;
See a more complete site search example for usage.