File size: 5,290 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
import { useMemo, useRef, useState } from 'react';

import { dequal } from '../lib/dequal';
import { getIndexSearchResults } from '../lib/getIndexSearchResults';
import { useIndexContext } from '../lib/useIndexContext';
import { useInstantSearchContext } from '../lib/useInstantSearchContext';
import { useInstantSearchServerContext } from '../lib/useInstantSearchServerContext';
import { useStableValue } from '../lib/useStableValue';
import { useWidget } from '../lib/useWidget';

import type { Connector, Widget, WidgetDescription } from 'instantsearch.js';

export type AdditionalWidgetProperties = Partial<Widget<WidgetDescription>>;

export function useConnector<
  TProps extends Record<string, unknown>,
  TDescription extends WidgetDescription
>(
  connector: Connector<TDescription, TProps>,
  props: TProps = {} as TProps,
  additionalWidgetProperties: AdditionalWidgetProperties = {}
): TDescription['renderState'] {
  const serverContext = useInstantSearchServerContext();
  const search = useInstantSearchContext();
  const parentIndex = useIndexContext();
  const stableProps = useStableValue(props);
  const stableAdditionalWidgetProperties = useStableValue(
    additionalWidgetProperties
  );
  const shouldSetStateRef = useRef(true);
  const previousRenderStateRef = useRef<TDescription['renderState'] | null>(
    null
  );

  const widget = useMemo(() => {
    const createWidget = connector(
      (connectorState, isFirstRender) => {
        // We skip the `init` widget render because:
        // - We rely on `getWidgetRenderState` to compute the initial state before
        //   the InstantSearch.js lifecycle starts.
        // - It prevents UI flashes when updating the widget props.
        if (isFirstRender) {
          shouldSetStateRef.current = true;
          return;
        }

        // There are situations where InstantSearch.js may render widgets slightly
        // after they're removed by React, and thus try to update the React state
        // on unmounted components. React 16 and 17 consider them as memory leaks
        // and display a warning.
        // This happens in <DynamicWidgets> when `attributesToRender` contains a
        // value without an attribute previously mounted. React will unmount the
        // component controlled by that attribute, but InstantSearch.js will stay
        // unaware of this change until the render pass finishes, and therefore
        // notifies of a state change.
        // This ref lets us track this situation and ignore these state updates.
        if (shouldSetStateRef.current) {
          const { instantSearchInstance, widgetParams, ...renderState } =
            connectorState;

          // We only update the state when a widget render state param changes,
          // except for functions. We ignore function reference changes to avoid
          // infinite loops. It's safe to omit them because they get updated
          // every time another render param changes.
          if (
            !dequal(
              renderState,
              previousRenderStateRef.current,
              (a, b) =>
                a?.constructor === Function && b?.constructor === Function
            )
          ) {
            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            setState(renderState);
            previousRenderStateRef.current = renderState;
          }
        }
      },
      () => {
        // We'll ignore the next state update until we know for sure that
        // InstantSearch.js re-inits the component.
        shouldSetStateRef.current = false;
      }
    );

    return {
      ...createWidget(stableProps),
      ...stableAdditionalWidgetProperties,
    };
  }, [connector, stableProps, stableAdditionalWidgetProperties]);

  const [state, setState] = useState<TDescription['renderState']>(() => {
    if (widget.getWidgetRenderState) {
      // The helper exists because we've started InstantSearch.
      const helper = parentIndex.getHelper()!;
      const uiState = parentIndex.getWidgetUiState({})[
        parentIndex.getIndexId()
      ];
      helper.state =
        widget.getWidgetSearchParameters?.(helper.state, { uiState }) ||
        helper.state;
      const { results, scopedResults } = getIndexSearchResults(parentIndex);

      // We get the widget render state by providing the same parameters as
      // InstantSearch provides to the widget's `render` method.
      // See https://github.com/algolia/instantsearch.js/blob/019cd18d0de6dd320284aa4890541b7fe2198c65/src/widgets/index/index.ts#L604-L617
      const { widgetParams, ...renderState } = widget.getWidgetRenderState({
        helper,
        parent: parentIndex,
        instantSearchInstance: search,
        results,
        scopedResults,
        state: helper.state,
        renderState: search.renderState,
        templatesConfig: search.templatesConfig,
        createURL: parentIndex.createURL,
        searchMetadata: {
          isSearchStalled: search.status === 'stalled',
        },
        status: search.status,
        error: search.error,
      });

      return renderState;
    }

    return {};
  });

  useWidget({
    widget,
    parentIndex,
    props: stableProps,
    shouldSsr: Boolean(serverContext),
  });

  return state;
}