react-instantsearch icon indicating copy to clipboard operation
react-instantsearch copied to clipboard

[react-instantsearch-hooks] RefinementList search state cleared on un-mount even when using useRefinementList to create a virtual widget

Open jamespeilow opened this issue 3 years ago • 5 comments

🐛 Bug description

When placing a <RefinementList> component inside a modal component that mounts and un-mounts its content, the current refinements are cleared even when using the useRefinementsList hook to create a virtual refinement list widget.

🔍 Bug reproduction

Minimal example set up on Codesandbox, using the Algolia docs example as a reference.

Steps to reproduce the behavior:

  1. Go to https://codesandbox.io/s/snowy-field-22wyku?file=/src/App.js
  2. Click on the "Show DIalog" button to open the modal
  3. Apply a refinement (notice that the hits have updated)
  4. Close the modal by clicking outside the modal body
  5. The refinement has reset and all results show (refinement state has been cleared)

Live reproduction:

https://codesandbox.io/s/snowy-field-22wyku?file=/src/App.js

💭 Expected behavior

Current refinement search state should be preserved when the <RefinementList> component inside the modal component is unmounted on close.

Environment

  • React InstantSearch Hooks version: 6.29.0
  • React version: 18.0.0
  • Browser: Chrome 103.0.5060.53
  • OS: macOS

Thanks

jamespeilow avatar Jun 29 '22 14:06 jamespeilow

Unfortunately this isn't yet possible. There's two possible workarounds:

  1. if you're making a custom widget anyway, make the layout like this:
function RefinementList() {
  useRefinementList()
  
  return <Dialog />
}
  1. use a dialog that only hides via css, but keeps the refinement in the tree

We don't yet have a mechanism to prevent a widget from cleaning up when it unmounts, even when there's another widget of the same type in the tree, as it's impossible to detect both are intended to be synced

Haroenv avatar Jun 29 '22 14:06 Haroenv

Here's how to use the internal ui component to avoid recreating the whole rendering and still put the dialog inside the refinement list conceptually: https://codesandbox.io/s/autumn-leftpad-3j3nmp?file=/src/App.js

Haroenv avatar Jun 29 '22 14:06 Haroenv

We are running into the same issue. We use a drawer like structure on mobile, while keeping the desktop UI components mounted. The drawer is a component from @chakra-ui/react, of which we can't control the mounting state (it gets unmounted on close) https://chakra-ui.com/docs/components/drawer

The drawer opens if you click a filter button, the user can apply refinements within the drawer but once the drawer closes, all filters cleared (as the drawer simply renders all the filters within). It feels like unexpected behaviour, as I would expect the lib to keep track of the mounted widgets

We'll look intro restructuring our component tree for now.

[edit] please note that both the desktop and mobile UI use hooks

The documentation actually seems to suggest that the @jamespeilow is pointing out should actually work: https://www.algolia.com/doc/guides/building-search-ui/widgets/customize-an-existing-widget/react-hooks/#building-a-virtual-widget-with-hooks

RobbyUitbeijerse avatar Jul 22 '22 10:07 RobbyUitbeijerse

had another look the connect example from here which uses a modal https://www.algolia.com/doc/guides/building-search-ui/going-further/native/react/#create-a-modal

it can also be done in hooks by using const { setUiState } = useInstantSearch() and wrapping the modal in another InstantSearch instance

const VirtualUiState = ({ searchState }) => {
  const { setUiState } = useInstantSearch();
  useEffect(() => {
    setUiState(searchState);
  }, [setUiState, searchState]);

  return null;
};
const VirtualRefinementList = ({ attribute, searchState }) => {
  useRefinementList({ attribute });
 return null
};
...
const [searchState, setSearchState] = useState({})
const handleStateChange = ({ uiState, setUiState }) => {
  const nextState = {...uiState} // or custom merge
  setSearchState(nextState);
  setUiState(nextState);
}
...
<InstantSearch searchClient={searchClient} indexName="instant_search" >
<VirtualUiState searchState={searchState} />
<VirtualRefinementList searchState={searchState} attribute={attribute} /> 
{filterVisible && (
                <InstantSearch
                  searchClient={searchClient}
                  indexName="instant_search"
                  onStateChange={handleStateChange}
                  initialUiState={searchState}
                >
                  <Panel header={attribute}>
                    <RefinementList attribute={attribute} />
                  </Panel>
                </InstantSearch>
              )}
</InstantSearch>

working version here https://codesandbox.io/s/snowy-leftpad-cbln77?file=/src/App.tsx:954-1145

@Haroenv the hooks documentation should be updated with this example

fatlinesofcode avatar Sep 21 '22 12:09 fatlinesofcode

We've fixed this issue in our app with this wrapper component for a widget to prevent the unloading state behaviour

const WidgetUiStateProvider = ({
  indexName,
  children,
  searchClient,
  syncWithRootUiState = true,
}) => {
  const {
    uiState: rootUiState,
    setUiState: setRootUiState,
  } = useInstantSearch();

  const handleStateChange = ({ uiState, setUiState }) => {
    if (syncWithRootUiState) {
      setUiState(uiState);
      setRootUiState(uiState);
    }
  };

  return (
    <InstantSearch
      indexName={indexName}
      searchClient={searchClient}
      onStateChange={handleStateChange}
      initialUiState={rootUiState}
    >
      {children}
    </InstantSearch>
  );
};

it can be used like so

<InstantSearch searchClient={searchClient} indexName="instant_search">
          <Configure hitsPerPage={8} />
         <VirtualRefinementList attribute={attribute} />
...

{filterVisible && (
                <WidgetUiStateProvider
                  searchClient={searchClient}
                  indexName="instant_search"
                >
                  <Panel header={attribute}>
                    <RefinementList attribute={attribute} />
                  </Panel>
                </WidgetUiStateProvider>
              )}

...
</InstantSearch>

https://codesandbox.io/s/solitary-mountain-d47veh?file=/src/App.tsx:2708-3066

fatlinesofcode avatar Sep 23 '22 00:09 fatlinesofcode

This is the fiddliest thing I've dealt with today. Thankyou @fatlinesofcode for the hint, would not have figured this out without your help. A note on my struggles implementing it in my code:

  • You need to do the unmount in the same function containing the widgetuistateprovider (ie don't unmount in a custom refinementlist)
  • The virtualrefinementlist needs to be mounted always.

brensch avatar Sep 30 '22 07:09 brensch

To anyone who doesn't want the added complexity of maintaining search state and virtual widgets just to get a drawer working w/ React on mobile, Material UI drawer has the ability to hide without unmounting, so you can use regular refinement lists without any of the workarounds above. Funny enough, I love Chakra UI and my entire project uses it except for just this single drawer on mobile breakpoints 😝.

Material UI drawer: https://mui.com/material-ui/react-drawer/

<Drawer
  anchor={'left'}
  open={isDrawerIsOpen}
  onClose={handleClose}
  variant="temporary"
  ModalProps={{
    keepMounted: true,
  }}
>

CMLivingston avatar Nov 04 '22 19:11 CMLivingston