fix(clerk-js): Fetching custom role in OrganizationSwitcher with cache#2430
fix(clerk-js): Fetching custom role in OrganizationSwitcher with cache#2430panteliselef merged 7 commits intomainfrom
Conversation
In order to do this efficiently and to avoid requesting everytime the switcher opens, a simple cache inside useFetch was implemented.
🦋 Changeset detectedLatest commit: 67c450c The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
2724193 to
033fba3
Compare
brkalow
left a comment
There was a problem hiding this comment.
We need to tweak the logic around params in useCache to ensure we're dealing with a stable cache key.
| const requestStatus = useLoadingStatus({ | ||
| status: 'loading', | ||
| }); | ||
| const cache = useCache(params); |
There was a problem hiding this comment.
It appears that params is regularly an object here that is not memoized. If I'm understanding the useCache implementation correctly, we're using the raw params value as a cache key. This means that every re-render could potentially introduce a new entry in the cache. We likely need to stringify the object in a deterministic way (e.g. sorted) to get a consistent cache key (I see we're doing it below).
Additionally, the useCallback usage within useCache is not so useful for the same reason (params changing reference on each call).
There was a problem hiding this comment.
Thanks for caching this @brkalow, shall i go the stringify approach ?
Description
Problem
In order to display a custom role we need to fetch them, so far we didn't have a robust way of fetching resources in clerk-js. A while back i had implemented
useFetch, today I'm extending it in order to use a cache in order to fetch and share resources across components more efficiently.Before
When a component need to display the custom roles we had to fetch those each time the component was mounted.
After
We fetch the resource once, other subscribers will not trigger a refetch unless the data is stale (in cache for 2 mins).
Goal
The goal of this PR is to provide a good enough fix for the issue with an efficient solution. This is a bug in v4 as well, and a simple solution is better when backporting is necessary. If we think this solution is limiting, we should consider migrating to swr as its bundlesize is minimal and much more robust.
For tests:
Checklist
npm testruns as expected.npm run buildruns as expected.Type of change
Packages affected
@clerk/backend@clerk/chrome-extension@clerk/clerk-js@clerk/clerk-expo@clerk/fastifygatsby-plugin-clerk@clerk/localizations@clerk/nextjs@clerk/clerk-react@clerk/remix@clerk/clerk-sdk-node@clerk/shared@clerk/themes@clerk/typesbuild/tooling/chore