UNPKG

@dotcms/react

Version:

Official React Components library to render a dotCMS page.

120 lines (117 loc) 2.96 kB
import { useReducer, useRef, useEffect, useCallback } from 'react'; import { DotCMSEntityState } from '@dotcms/types'; function reducer(state, action) { switch (action.type) { case DotCMSEntityState.LOADING: return Object.assign({}, state, { status: { state: DotCMSEntityState.LOADING } }); case DotCMSEntityState.SUCCESS: return { response: action.payload, status: { state: DotCMSEntityState.SUCCESS } }; case DotCMSEntityState.ERROR: return Object.assign({}, state, { status: { state: DotCMSEntityState.ERROR, error: action.payload } }); case DotCMSEntityState.IDLE: return { response: null, status: { state: DotCMSEntityState.IDLE } }; default: return state; } } /** * Hook to search for contentlets using AI. * @template T - The type of the contentlet. * @param client - The client to use for the search. * @param indexName - The name of the index to search in. * @param params - The parameters for the search. * @returns The search results. * * @example * ```typescript * const { results, status, search, reset } = useAISearch<BlogPost>({ * client: dotCMSClient, * indexName: 'blog-search-index', * params: { * query: { * limit: 10, * offset: 0, * contentType: 'Blog' * }, * config: { * threshold: 0.5, * responseLength: 1024 * } * } * }); * ``` */ const useAISearch = ({ client, indexName, params }) => { var _state$response$resul, _state$response; const [state, dispatch] = useReducer(reducer, { response: null, status: { state: DotCMSEntityState.IDLE } }); // Use ref to store params so search callback doesn't change when params change const paramsRef = useRef(params); // Keep ref updated with latest params useEffect(() => { paramsRef.current = params; }, [params]); const reset = useCallback(() => { dispatch({ type: DotCMSEntityState.IDLE }); }, []); const search = useCallback(async prompt => { if (!prompt.trim()) { dispatch({ type: DotCMSEntityState.IDLE }); return; } dispatch({ type: DotCMSEntityState.LOADING }); try { const response = await client.ai.search(prompt, indexName, Object.assign({}, paramsRef.current)); dispatch({ type: DotCMSEntityState.SUCCESS, payload: response }); } catch (error) { dispatch({ type: DotCMSEntityState.ERROR, payload: error }); } }, [client, indexName]); return { response: state.response, results: (_state$response$resul = (_state$response = state.response) == null ? void 0 : _state$response.results) != null ? _state$response$resul : [], status: state.status, search, reset }; }; export { useAISearch };