Skip to content

compare function returning true still updates cache #906

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

Closed
pablen opened this issue Jan 15, 2021 · 2 comments · Fixed by #907
Closed

compare function returning true still updates cache #906

pablen opened this issue Jan 15, 2021 · 2 comments · Fixed by #907
Labels
area: cache bug Something isn't working

Comments

@pablen
Copy link

pablen commented Jan 15, 2021

Bug report

Description / Observed Behavior

When using a custom compare function and the comparison returns true, the data returned correctly keeps its current value, but the cached value still updates. This causes data to use the last received value when the component remounts and not the intended initial value we wanted to cache.

Expected Behavior

From reading the documentation I was expecting the cache to be persisted if a comparison returns true.

Repro Steps / Code Example

https://codesandbox.io/s/swr-using-compare-zn185?file=/src/App.tsx

  1. click to mount the component
  2. click "force revalidate" to... force some revalidates, and check data is correctly persisted.
  3. click unmount to unmount the component
  4. click mount again and check that data value is not the previously persisted value but the value of the last call

Additional Context

In my use case, the server response contains urls of images with timestamps that I want to exclude from the data diff in order to avoid re-downloading images the browser has in disk cache.

swr v0.4.0

@promer94
Copy link
Collaborator

Thanks for your detailed repro 🙏

For your specific use case. I think you could filter the data in the fetcher function, which might be more easier.

const result = [{
  image: 'xxx',
  timestamp: 'xxx'
}]

const fetcher = () => Promise.resolve(result).then(result => result.map(item => ({ image: item.image })))
const { data } = useSWR('/api', fetcher)

Writing a compare function sometimes could be a trick problem. so we use dequal as our default compare function.

@pablen
Copy link
Author

pablen commented Jan 17, 2021

Thank for the suggestion @promer94!

Unfortunately my real use case is a bit more nuanced and I actually need the timestamp and other variable parts of the response to use in my component. The compare feature is exactly what I need to update the cache conditionally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area: cache bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants