Gathering detailed insights and metrics for swr-store
Gathering detailed insights and metrics for swr-store
npm install swr-store
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (95.54%)
JavaScript (4.46%)
Total Downloads
7,704,452
Last Day
14,609
Last Week
60,617
Last Month
270,041
Last Year
6,304,400
7 Stars
134 Commits
3 Watching
1 Branches
1 Contributors
Minified
Minified + Gzipped
Latest Version
0.10.6
Package Id
swr-store@0.10.6
Unpacked Size
131.51 kB
Size
23.70 kB
File Count
29
NPM Version
lerna/6.5.1/node@v19.6.0+x64 (win32)
Node Version
19.6.0
Publised On
21 Feb 2023
Cumulative downloads
Total Downloads
Last day
-14.4%
14,609
Compared to previous day
Last week
-8.8%
60,617
Compared to previous week
Last month
28.7%
270,041
Compared to previous month
Last year
351.7%
6,304,400
Compared to previous year
1
6
Reactive SWR stores for data-fetching.
1npm install --save swr-store
1yarn add swr-store
1import { createSWRStore, trigger } from 'swr-store'; 2 3const dogAPI = createSWRStore<APIResult, [string]>({ 4 // Fetch data based on breed 5 get: async (breed: string) => { 6 const response = await fetch(`${API}${breed}${API_SUFFIX}`); 7 return (await response.json()) as APIResult; 8 }, 9 // Allow us to revalidate the data 10 // whenever the page gets focused 11 revalidateOnFocus: true, 12 13 // Revalidate the data when the network goes 14 // back online 15 revalidateOnNetwork: true, 16}); 17 18// Will be pending initially. 19// The result will change once dogAPI.get is called again 20// sometime after the fetch has assumed to be resolved. 21const result = dogAPI.get(['shiba']); 22 23if (result.status === 'pending') { 24 displaySkeleton(); 25} else if (result.status === 'failure') { 26 displayFallback(); 27} else if (result.status === 'success') { 28 displayUI(result.data); 29} 30 31// When click is triggered, we prompt a revalidation process 32document.getElementById('#refresh').addEventListener('click', () => { 33 // We can do local revalidation 34 dogAPI.trigger(['shiba']); 35 36 // Or a global revalidation 37 trigger('shiba'); 38});
SWR stores may derive keys based on received arguments. These keys are used to locate cache references. By default, arguments are serialized through JSON.stringify
, but can be overriden by providing options.key
, where the key
function receives the arguments and may return a string.
1const store = createSWRStore({
2 // Only select the key
3 // note that keys are globally shared.
4 key: (id) => id,
5
6 // An auth-based endpoint
7 get: (id, token) => getUserPrivateData({
8 userId: id,
9 token,
10 }),
11});
12
13// ...
14const privateData = store.get(userId, userToken);
SWR store allows subscriptions to subscribe for cache updates. Subscribing returns a callback that allows unsubscribing to the cache updates.
1 2// Local subscription 3const unsubscribe = userDetails.subscribe([userId], (result) => { 4 if (result.status === 'pending') { 5 displaySkeleton(); 6 } else if (result.status === 'failure') { 7 displayFallback(); 8 } else if (result.status === 'success') { 9 displayUI(result.data); 10 } 11}); 12 13// global subscription 14import { subscribe } from 'swr-store'; 15 16const unsubscribe = subscribe(`/user/${userId}`, (result) => { 17 if (result.status === 'pending') { 18 displaySkeleton(); 19 } else if (result.status === 'failure') { 20 displayFallback(); 21 } else if (result.status === 'success') { 22 displayUI(result.data); 23 } 24});
SWR store may present an initial data through options.initialData
. This data is used only when the store finds an empty cache value. Initial data is also useful for opting-out of initial pending phase and providing a way for SSR pages to hydrate stores.
1const userDetails = createSWRStore({ 2 get: (id) => getUserDetails(id), 3 4 initialData: prefetchedData, 5});
Stores can also be hydrated manually through mutate
.
Calling store.get
also allows lazy hydration, in which the provided initial data is preferred rather than options.initialData
.
1const result = userDetails.get([userId], { 2 // If there's no cache, prefetched data is used 3 // then attempts revalidation 4 initialData: prefetchedData, 5});
Do note that options.initialData
won't hydrate the actual store but present a fallback data when the result is still pending. You can use options.hydrate
to overwrite the current cached data.
SWR stores are lazily revalidated whenever store.get
is called.
1// Initial fetch 2const result = store.get([]); 3 4setTimeout(() => { 5 // May contain the resolved result 6 // or a new one if the cache has been invalidated. 7 const newResult = store.get([]); 8});
Revalidation on get
may be opt-out by providing shouldRevalidate
:
1const result = store.get([], { 2 shouldRevalidate: false, 3});
SWR stores share the same global cache, and can be prompted with a global manual revalidation. trigger
and mutate
are similar to store's store.trigger
and store.mutate
except that they accept the cache key instead of the store's expected arguments.
Stores subscribers are may be notified (trigger
does not guarantee a notification, while mutate
guarantees a notification) for the cache update.
1import { trigger, mutate } from 'swr-store'; 2 3const userDetails = createSWRStore({ 4 // Transform id into a cache key 5 key: (id) => `/user/${id}`, 6 7 // An auth-based endpoint 8 get: (id) => getUserDetails(id), 9}); 10 11// ... 12// Global trigger 13trigger(`/user/${userId}`); 14 15// Or mutate 16mutate(`/user/${userId}`, { 17 data: { 18 name: 'John Doe', 19 age: 16, 20 }, 21 status: 'success', 22});
SWR stores can be manually revalidated by calling store.trigger
or store.mutate
.
store.trigger(args, shouldRevalidate = true)
: Triggers a revalidation from the given arguments. Arguments are passed to options.key
to locate the cache.store.mutate(args, result, shouldRevalidate = true)
: Mutates the cache with result
. Cache is located based on the key generated from the arguments passed to options.key
.1// Local revalidation 2userDetails.trigger([userId]); 3 4// is the same as 5trigger(`/user/${userId}`); 6 7// Since userDetails yields the same key format.
SWR stores are able to automatically revalidate data based on DOM events. This feature can be activated based on the following options:
options.revalidateOnFocus
: Automatically revalidates data when the window 'focus'
event is triggered. Defaults to false
.options.revalidateOnVisibility
: Automatically revalidates data when the document 'visibilitychange'
event is triggered, specifically, if the page is 'visible'
. Defaults to false
.options.revalidateOnNetwork
: Automatically revalidates data when the window 'online'
event is triggered. Defaults to false
.SWR stores are able to poll for revalidation. They are different to event-based revalidation as polling revalidation happens in intervals.
This behavior can be activated through the following options:
options.refreshInterval
: Amount of time (in milliseconds) the revalidation goes through in intervals. Defaults to undefined
(Does not poll). Polling begins immediately after the lazy setup has been triggered.The default behavior can be overriden by the following options:
options.refreshWhenHidden
: Overrides the default polling behavior and only begins polling after the page becomes hidden (triggered by document visibilitychange
event.). Once the document becomes visible, polling halts.options.refreshWhenBlurred
: Overrides the default polling behavior and only begins polling after the page loses focus (triggered by window blur
and focus
events). Once the page is focused again, polling halts.options.refreshWhenOffline
: Overrides the default polling behavior and only begins polling after the page becomes offline (triggered by window offline
and online
events). Once the page is focused again, polling halts.SWR stores are lazily setup: polling and automatic revalidation only begins when there are subscribers to the stores. Once a store receives a subscriber (through store.subscribe
method), the store lazily sets up the revalidation processes, this way, automatic processes are conserved and are only added when needed.
Stores also halt from automatic revalidation if they lose all subscribers through reference-counting.
SWR stores can define how 'fresh' or 'stale' the cache is, which can alter the revalidation behavior:
'pending'
state.These behavior can be defined through the following options:
options.freshAge
: Defines how long the cache stays 'fresh', in milliseconds. Defaults to 2000
. (2 seconds).options.staleAge
: Defines how long the cache stays 'stale' after becoming 'fresh', in milliseconds. Defaults to 30000
(30 seconds).A cache is 'fresh' when the time between the cache was updated and was read is between the options.freshAge
value, otherwise, the cache automatically becomes 'stale'.
A cache that has been 'stale' will continue being 'stale' until the time between the cache became 'stale' and was read is between the options.staleAge
.
Cache invalidation always happen lazily: checking for cache age only happens when the revalidation process is requested upon (usually automatically through polling or revalidation on events) or manually (mutate
or trigger
).
SWR Stores throttles data fetching processes through the caching strategy. Cache maintain a timestamp internally, marking valid requests and cache references, establishing race conditions.
SWR stores' cache revalidation and data-fetching only happens on client-side.
SWR stores, by default, deeply compare success data in between cache updates. This behavior prevents re-notifying subscribers when the contents of the data remains the same. This behavior can be overriden by providing a compare function in options.compare
.
mutate
accepts an custom compare function to override this behavior as a fourth parameter.
SWR stores implements the exponential backoff algorithm for retry intervals whenever a request fails. By default, SWR stores retry indefinitely until the request resolves successfully at a maximum interval of 5000ms
. Limit can be defined through options.maxRetryCount
and the interval can be overriden with options.maxRetryInterval
.
MIT © lxsmnsyc
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
no SAST tool detected
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
security policy file not detected
Details
Reason
25 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More