Cache miss when transforming value with useMemo()
See original GitHub issueBug report
Description / Observed Behavior
I am using dependant SWR requests. The first one is fetching an array of users, the second one is fetching additional information for each individual user. In order to reduce the amount of requests I filter the array of user for only active ones using useMemo()
.
Although the resulting array of filtered user is exactly the same between page transition, it results in a cache miss (which means it doesn’t return the cached value, instead waiting for the async request to complete).
Expected Behavior
I expect SWR to return stale data first when I use exactly the same key + data input between page transitions.
Repro Steps / Code Example
I created a Code Sandbox to reproduce the behaviour. CodeSandbox
Additional Context
My understanding is, that for dedouping we use dequal
, which does a deep comparisons. I have found some information about how we evaluate, if the cache can provide stale data. The key is essential, but also the dependent data passed alongside the key is relevant. Here I expected also a deep comparison, but according to my example it doesn’t seem to be the case.
Am I missing something?
SWR 0.5.6 React 17.0.2
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (2 by maintainers)
@gonzochic Using
JSON.stringify
andJSON.parse
seems like a reasonable approach to me with some caveats:JSON.stringify
doesn’t guarantee the order of the keys in the string, so it could be better to use something likejson-stable-stringify
.I’ve looked through the docs to see if there’s a general answer for how to handle this, but I haven’t found one. I remember reading in some issues that the recommended approach is to spread the nested array into the array that represents the
useSWR
key. Though, there are limitations to this approach as well.Closing since key serialization was added in #1429 and released as 1.1.0-beta.0, you don’t need
useMemo
anymore! 🎉