Skip to content

fix(react-instantsearch-core): Preserve helper state during freeze/unfreeze operations #6629

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 30 additions & 5 deletions packages/react-instantsearch-core/src/lib/useIndex.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import index from 'instantsearch.js/es/widgets/index/index';
import { useMemo } from 'react';
import { useMemo, useRef } from 'react';

import { useForceUpdate } from './useForceUpdate';
import { useIndexContext } from './useIndexContext';
Expand All @@ -20,12 +20,18 @@ export function useIndex(props: UseIndexProps) {
const parentIndex = useIndexContext();
const stableProps = useStableValue(props);
const indexWidget = useMemo(() => index(stableProps), [stableProps]);
const helper = indexWidget.getHelper();
const helperRef = useRef<any>(null);
const forceUpdate = useForceUpdate();

useIsomorphicLayoutEffect(() => {
forceUpdate();
}, [helper, forceUpdate]);
const currentHelper = indexWidget.getHelper();
if (helperRef.current === null || currentHelper !== helperRef.current) {
helperRef.current = currentHelper;
if (helperRef.current !== null) {
forceUpdate();
}
}
}, [indexWidget, forceUpdate]);

useWidget({
widget: indexWidget,
Expand All @@ -34,5 +40,24 @@ export function useIndex(props: UseIndexProps) {
shouldSsr: Boolean(serverContext || initialResults),
});

return indexWidget;
return useMemo(
() => ({
...indexWidget,
getHelper: () => {
const currentHelper = indexWidget.getHelper();

if (currentHelper !== null) {
helperRef.current = currentHelper;
return currentHelper;
}

if (helperRef.current !== null) {
return helperRef.current;
}

return null;
},
}),
[indexWidget]
);
}