File size: 6,631 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import InstantSearch from 'instantsearch.js/es/lib/InstantSearch';
import { useCallback, useRef, version as ReactVersion } from 'react';
import { useSyncExternalStore } from 'use-sync-external-store/shim';

import { useInstantSearchServerContext } from '../lib/useInstantSearchServerContext';
import { useInstantSearchSSRContext } from '../lib/useInstantSearchSSRContext';
import version from '../version';

import { useForceUpdate } from './useForceUpdate';

import type {
  InstantSearchOptions,
  SearchClient,
  UiState,
} from 'instantsearch.js';

const defaultUserAgents = [
  `react (${ReactVersion})`,
  `react-instantsearch (${version})`,
  `react-instantsearch-hooks (${version})`,
];
const serverUserAgent = `react-instantsearch-server (${version})`;

export type UseInstantSearchApiProps<
  TUiState extends UiState,
  TRouteState
> = InstantSearchOptions<TUiState, TRouteState>;

export function useInstantSearchApi<TUiState extends UiState, TRouteState>(
  props: UseInstantSearchApiProps<TUiState, TRouteState>
) {
  const forceUpdate = useForceUpdate();
  const serverContext = useInstantSearchServerContext<TUiState, TRouteState>();
  const serverState = useInstantSearchSSRContext();
  const initialResults = serverState?.initialResults;
  const searchRef = useRef<InstantSearch<TUiState, TRouteState> | null>(null);
  const prevPropsRef = useRef(props);

  if (searchRef.current === null) {
    // We don't use the `instantsearch()` function because it comes with other
    // top-level APIs that we don't need.
    // See https://github.com/algolia/instantsearch.js/blob/5b529f43d8acc680f85837eaaa41f7fd03a3f833/src/index.es.ts#L63-L86
    const search = new InstantSearch(props);

    if (serverContext || initialResults) {
      // InstantSearch.js has a private Initial Results API that lets us inject
      // results on the search instance.
      // On the server, we default the initial results to an empty object so that
      // InstantSearch.js doesn't schedule a search that isn't used, leading to
      // an additional network request. (This is equivalent to monkey-patching
      // `scheduleSearch` to a noop.)
      search._initialResults = initialResults || {};
    }

    addAlgoliaAgents(props.searchClient, [
      ...defaultUserAgents,
      serverContext && serverUserAgent,
    ]);

    // On the server, we start the search early to compute the search parameters.
    // On SSR, we start the search early to directly catch up with the lifecycle
    // and render.
    if (serverContext || initialResults) {
      search.start();
    }

    if (serverContext) {
      // We notify `getServerState()` of the InstantSearch internals to retrieve
      // the server state and pass it to the render on SSR.
      serverContext.notifyServer({ search });
    }

    searchRef.current = search;
  }

  {
    const search = searchRef.current;
    const prevProps = prevPropsRef.current;

    if (prevProps.indexName !== props.indexName) {
      search.helper!.setIndex(props.indexName).search();
      prevPropsRef.current = props;
    }

    if (prevProps.searchClient !== props.searchClient) {
      addAlgoliaAgents(props.searchClient, [
        ...defaultUserAgents,
        serverContext && serverUserAgent,
      ]);
      search.mainHelper!.setClient(props.searchClient).search();
      prevPropsRef.current = props;
    }

    if (prevProps.onStateChange !== props.onStateChange) {
      search.onStateChange = props.onStateChange;
      prevPropsRef.current = props;
    }

    if (prevProps.searchFunction !== props.searchFunction) {
      // Updating the `searchFunction` to `undefined` is not supported by
      // InstantSearch.js, so it will throw an error.
      // This is a fair behavior until we add an update API in InstantSearch.js.
      search._searchFunction = props.searchFunction;
      prevPropsRef.current = props;
    }

    if (prevProps.stalledSearchDelay !== props.stalledSearchDelay) {
      // The default `stalledSearchDelay` in InstantSearch.js is 200ms.
      // We need to reset it when it's undefined to get back to the original value.
      search._stalledSearchDelay = props.stalledSearchDelay ?? 200;
      prevPropsRef.current = props;
    }

    // Updating the `routing` prop is not supported because InstantSearch.js
    // doesn't let us change it. This might not be a problem though, because `routing`
    // shouldn't need to be dynamic.
    // If we find scenarios where `routing` needs to change, we can always expose
    // it privately on the InstantSearch instance. Another way would be to
    // manually inject the routing middleware in this library, and not rely
    // on the provided `routing` prop.
  }

  const cleanupTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const store = useSyncExternalStore<InstantSearch<TUiState, TRouteState>>(
    useCallback(() => {
      const search = searchRef.current!;

      // Scenario 1: the component mounts.
      if (cleanupTimerRef.current === null) {
        // On SSR, the instance is already started so we don't start it again.
        if (!search.started) {
          search.start();
          forceUpdate();
        }
      }
      // Scenario 2: the component updates.
      else {
        // We cancel the previous cleanup function because we don't want to
        // dispose the search during an update.
        clearTimeout(cleanupTimerRef.current);
        search._preventWidgetCleanup = false;
      }

      return () => {
        function cleanup() {
          search.dispose();
        }

        // We clean up only when the component that uses this subscription unmounts,
        // but not when it updates, because it would dispose the instance, which
        // would remove all the widgets and break routing.
        // Executing the cleanup function in a `setTimeout()` lets us cancel it
        // in the next effect.
        // (There might be better ways to do this.)
        cleanupTimerRef.current = setTimeout(cleanup);

        // We need to prevent the `useWidget` cleanup function so that widgets
        // are not removed before the instance is disposed, triggering
        // an unwanted search request.
        search._preventWidgetCleanup = true;
      };
    }, [forceUpdate]),
    () => searchRef.current,
    () => searchRef.current
  );

  return store;
}

function addAlgoliaAgents(
  searchClient: SearchClient,
  userAgents: Array<string | null>
) {
  if (typeof searchClient.addAlgoliaAgent !== 'function') {
    return;
  }

  userAgents.filter(Boolean).forEach((userAgent) => {
    searchClient.addAlgoliaAgent!(userAgent!);
  });
}