algolia / react-instantsearch

⚡️ Lightning-fast search for React and React Native applications, by Algolia.
https://www.algolia.com/doc/guides/building-search-ui/what-is-instantsearch/react/
MIT License
1.97k stars 386 forks source link

Instant Search Cache Never Cleared #2995

Closed allanohorn closed 3 years ago

allanohorn commented 3 years ago

The Bug My user updates a hit and so I want to refresh to incorporate the changes they just made. I know I'm supposed to b able to use the "refresh" toggle and clear my cache (or use a null cache) to show them up to date results, but it's not working properly. Specifically; in my network requests I see a new request go out and the correct data is coming back in, but when print out the hits in my "CustomInfiniteHits" component the cached data is being shown.

Root of the Problem I believe the problem is in connectInfiniteHits. The variable this._cachedHits gets set in two places.

When I first perform the search the variable is undefined and will be set to {}

    if (this._cachedHits === undefined) {
      this._cachedHits = cache.read({ state: searchState }) || {};
    }

If the searchState changes we will reset our cachedHits

    if (!isEqual(currentState, this._prevState)) {
      this._cachedHits = cache.read({ state: searchState }) || {};
    }
    if (this._cachedHits[page] === undefined) {
      this._cachedHits[page] = hitsWithPositionsAndQueryID;
      cache.write({ state: searchState, hits: this._cachedHits });
    }

Here is the rough sequence of events: 1) User opens the page and this._cachedHits gets set to {} at first then this._cachedHits[0] = myHits 2) User makes an update and I call searchClient.clearCache 3) I try to refresh but because currentState == this._prevState we never actually read from the cache again and end up continuing to use this._cachedHits

yannickcr commented 3 years ago

The InfiniteHits component has it's own internal cache that is different from the searchClient one. But you can override it the same way by using the cache props.

Here's an example of InfiniteHits with a null cache: https://codesandbox.io/s/bold-cherry-qbbup?file=/src/App.js

Haroenv commented 3 years ago

This is actually a bug in React InstantSearch, which has been fixed in InstantSearch.js in this issue: https://github.com/algolia/instantsearch.js/issues/4531

For now we have not yet fixed this bug in React InstantSearch, but porting that change here would definitely be welcome!

Haroenv commented 3 years ago

this is tracked in algolia/instantsearch.js#5263