`useSWR` in UI KIT library not using cache from consumer app
Bug report
useSWR in UI KIT library not using cache from consumer app
Description / Observed Behavior
I have 3 applications:
- UI KIT
- Consumer app 1
- Consumer app 2
And using useSWR inside of UI KIT components working but global mutate functions is not affecting consumer's app cache to revalidate.
I found that useSWR calls inside of UI KIT components using their own cache layer.
Expected Behavior
Global mutate function should work with app's cache
Additional Context
Projects using Vite typescript react and
"swr": "^2.2.4",
Reference: https://github.com/vercel/swr/discussions/2825
I can confirm that inside a monorepo when referencing a library from an app there is some kind of internal cache being utilized from the library export via useSWR and when reseting the cache in tests from the app, the app swr provider is cleared but not the internal cache from the useSWR from the lib.
There is only one provider for swr and it is in the tests, no other provider exists but some how two cache's are generated. If I move all of the library code into the app, all the tests pass.
using: swr: ^2.2.5
I guess we should provide a reproduction sandbox, but currently I don't have time :(
After some testing and a few suggestions from coworkers, the reason for this issue is that the node_modules/swr was in multiple locations, one in the app and one in the library. This caused two global caches respective to each instance of swr
This is probably a non-issue with importing into apps NOT in the monorepo but when you have multiple instances of swr per library or app it breaks.
tl;dr Should only use one node_modules/swr between all projects to access the same cache
I don't get it. Why having 2 swr packages in node_modules creates in runtime two instances of SWR?
There is a build step involved that will use only one package resolved from node modules, isn't it?
Additional context: Im using pnpm and npm package for UI KIT (not monorepo)
tl;dr Should only use one node_modules/swr between all projects to access the same cache
How to achive this? Installing swr as a peerDep instead of dep worked in your case?
I can confirm that problem related to which SWR instance I'm using. When I export from UI KIT function that calls it's mutate in it and call this function in external app — it works.
I'm thinking about making a wrapper around SWR and it's methods in UI KIT and exporting it:
// Something like that:
export SWR_INSTANCE = /* ... */;
// In consumer app:
import { mutate } from 'ui-kit/swr';
mutate('key'); // will work
Maybe somebody knows better solutions?
tl;dr Should only use one node_modules/swr between all projects to access the same cache
How to achive this? Installing swr as a peerDep instead of dep worked in your case?
For my case I made sure all my swr instances were using the same version, that way one 1 copy of swr is loaded from monorepo root