Gathering detailed insights and metrics for swr-global-state
Gathering detailed insights and metrics for swr-global-state
Gathering detailed insights and metrics for swr-global-state
Gathering detailed insights and metrics for swr-global-state
@zyda/swr-internal-state
Use SWR to manage app's internal state
x-state-manager
A lightweight state manager built on top of SWR for efficient state management with caching, optimistic updates, and modular architecture. It allows easy global and local state management, automatic data re-fetching on focus, and supports TypeScript
♻️ Zero-setup & simple global state management for React Components. It's similiar `useState` hooks like we use usual!
npm install swr-global-state
Typescript
Module System
Min. Node Version
Node Version
NPM Version
68.1
Supply Chain
98.8
Quality
76.2
Maintenance
100
Vulnerability
100
License
TypeScript (79.85%)
JavaScript (11.23%)
CSS (8.92%)
Total Downloads
15,443
Last Day
11
Last Week
65
Last Month
243
Last Year
5,459
43 Stars
199 Commits
1 Forks
1 Watching
1 Branches
1 Contributors
Minified
Minified + Gzipped
Latest Version
2.2.0
Package Id
swr-global-state@2.2.0
Unpacked Size
42.16 kB
Size
10.12 kB
File Count
12
NPM Version
9.6.7
Node Version
18.17.0
Publised On
28 Jul 2023
Cumulative downloads
Total Downloads
Last day
120%
11
Compared to previous day
Last week
1.6%
65
Compared to previous week
Last month
13%
243
Compared to previous month
Last year
-19.4%
5,459
Compared to previous year
3
Zero-setup & simple global state management for React Components based on SWR helpers. With this library, you can focus on your awesome React Project and not waste another afternoon on the setup & configuring your global state. 🌄
1npm i swr swr-global-state
1yarn add swr swr-global-state
Create a new file for your global state on your root directory. And then, use createStore
. Example: stores/counter.js
1// file: stores/counter.js 2 3import { createStore } from "swr-global-state"; 4 5const useCounter = createStore({ 6 key: "@app/counter", // (Required) state key with unique string 7 initial: 0 // <- (Required) initial state 8}); 9 10export default useCounter;
You just import stores that you have created into your any components, then use it like you use useState
as usual.
1// file: components/SetCountComponent.js 2 3import useCounter from "stores/counter"; 4 5function SetCountComponent() { 6 const [, setCount] = useCounter(); // <- `[, ]` skipping first index of the array. 7 return ( 8 <div> 9 <button onClick={() => setCount(prev => prev - 1)}> 10 (-) Decrease Count 11 </button> 12 13 <button onClick={() => setCount(prev => prev + 1)}> 14 (+) Increase Count 15 </button> 16 </div> 17 ); 18} 19 20export default SetCountComponent;
1// file: components/GetCountComponent.js 2 3import useCounter from "stores/counter"; 4 5function GetCountComponent() { 6 const [count] = useCounter(); 7 return ( 8 <div> 9 <p>Current Count: {count}</p> 10 </div> 11 ); 12} 13 14export default GetCountComponent;
Optionally, you can define persistor
object to create custom persistor to hold your state even user has closing app/browser, and re-opened it.
In this example, we use localStorage
to hold our state.
1// file: stores/counter.js
2
3import { createStore } from "swr-global-state";
4
5const useCounter = createStore({
6 key: "@app/counter",
7 initial: 0,
8 persistor: { // <- Optional, use this if you want hold the state
9 onSet: (key, data) => {
10 window.localStorage.setItem(String(key), data);
11 },
12 onGet: (key) => {
13 const cachedData = window.localStorage.getItem(String(key));
14 return Number(cachedData);
15 }
16 }
17});
18
19export default useCounter;
We can create reusable persistor
to re-use in every stores that we have created. Example:
1// file: persistors/local-storage.ts 2 3import type { StatePersistor, StateKey } from "swr-global-state"; 4 5const withLocalStoragePersistor = <T = any>(): StatePersistor<T> => ({ 6 onSet(key: StateKey, data: T) { 7 const stringifyData = JSON.stringify(data); 8 window.localStorage.setItem(String(key), stringifyData); 9 }, 10 onGet(key: StateKey) { 11 const cachedData = window.localStorage.getItem(String(key)) ?? "null"; 12 try { 13 return JSON.parse(cachedData); 14 } catch { 15 return cachedData; 16 } 17 } 18}); 19 20export default withLocalStoragePersistor;
Now, we can use that withLocalStoragePersistor
in that like this:
1// file: stores/counter.ts 2 3import { createStore } from "swr-global-state"; 4import withLocalStoragePersistor from "persistors/local-storage"; 5 6const useCounter = createStore<number>({ 7 key: "@app/counter", 8 initial: 0, 9 persistor: withLocalStoragePersistor() 10}); 11 12export default useCounter;
1// file: stores/theme.ts 2 3import { createStore } from "swr-global-state"; 4import withLocalStoragePersistor from "persistors/local-storage"; 5 6const useTheme = createStore<string>({ 7 key: "@app/theme", 8 initial: "light", 9 persistor: withLocalStoragePersistor() 10}); 11 12export default useTheme;
Just use async function or promise as usual in onSet
and onGet
.
1// file: stores/counter.js 2 3import AsyncStorage from '@react-native-async-storage/async-storage'; 4import { createStore } from "swr-global-state"; 5 6const useCounter = createStore({ 7 key: "@app/counter", 8 initial: 0, 9 persistor: { 10 async onSet(key, data) { 11 try { 12 await AsyncStorage.setItem(String(key), data); 13 } catch (err) { 14 // handle saving error, default throw an error 15 throw new Error(err); 16 } 17 }, 18 async onGet(key) { 19 try { 20 const value = await AsyncStorage.getItem(String(key)); 21 return Number(value); 22 } catch (err) { 23 // handle error reading value 24 throw new Error(err); 25 } 26 } 27 } 28}); 29 30export default useCounter;
Best practice in using persistor
is use Debouncing Technique. This example is using debouncing
in onSet
callback. So, it will not spamming to call the callback request every state changes.
1import AsyncStorage from '@react-native-async-storage/async-storage'; 2import { createStore } from "swr-global-state"; 3 4const withDebounce = (fn, time) => { 5 let timeoutId; 6 const wrapper = (...args) => { 7 if (timeoutId) { 8 clearTimeout(timeoutId); 9 } 10 timeoutId = setTimeout(() => { 11 timeoutId = null; 12 fn(...args); 13 }, time); 14 }; 15 return wrapper; 16}; 17 18const useUser = createStore({ 19 key: "@app/user", 20 initial: null, 21 persistor: { 22 onSet: withDebounce(async(key, user) => { 23 try { 24 const stringifyUser = JSON.stringify(user) 25 await AsyncStorage.setItem(String(key), stringifyUser); 26 } catch (err) { 27 // handle saving error, default throw an error 28 throw new Error(err); 29 } 30 }, 1000), // debounce-effect in 1 second. 31 ... 32 } 33}); 34 35export default useUser;
Can't find your cases in this documentation examples? You can create custom hooks by yourself. Here is complex example you can refer the pattern to create another custom hooks cases.
1// file: stores/account.js 2... 3import useStore from "swr-global-state"; 4 5const KEY = "@app/account"; 6 7function useAccount() { 8 const [loading, setLoading] = useStore({ 9 key: `${KEY}-loading`, 10 initial: true 11 }); 12 const [account, setAccount, swrDefaultResponse] = useStore( 13 { 14 key: KEY, 15 initial: null, 16 persistor: { 17 onSet: (key, accountData) => { 18 window.localStorage.setItem(String(key), JSON.stringify(accountData)); 19 }, 20 onGet: async(key) => { 21 if (window.navigator.onLine) { 22 const remoteAccount = await fetch('/api/account'); 23 return remoteAccount.json(); 24 } 25 const cachedAccount = window.localStorage.getItem(String(key)); 26 setLoading(false); 27 return JSON.parse(cachedAccount); 28 } 29 } 30 }, 31 { 32 /** 33 * set another SWR config here 34 * @see https://swr.vercel.app/docs/options#options 35 * @default on `swr-global-state`: 36 * revalidateOnFocus: false 37 * revalidateOnReconnect: false 38 * refreshWhenHidden: false 39 * refreshWhenOffline: false 40 */ 41 revalidateOnFocus: true, 42 revalidateOnReconnect: true 43 } 44 ); 45 46 /** 47 * Destructuring response from SWR Default response 48 * @see https://swr.vercel.app/docs/options#return-values 49 */ 50 const { mutate, error } = swrDefaultResponse; 51 52 const destroyAccount = async () => { 53 setLoading(true); 54 await fetch('/api/account/logout'); 55 window.localStorage.removeItem(KEY); 56 // use default `mutate` from SWR to avoid `onSet` callback in `persistor` 57 mutate(null); 58 setLoading(false); 59 }; 60 61 const updateAccount = async (newAccountData) => { 62 setLoading(true); 63 await fetch('/api/account', { 64 method: 'POST', 65 body: JSON.stringify(newAccountData) 66 ... 67 }) 68 setAccount(newAccountData); 69 setLoading(false); 70 }; 71 72 // your very custom mutator/dispatcher 73 74 return { 75 loading, 76 error, 77 account, 78 updateAccount, 79 destroyAccount 80 }; 81} 82 83export default useAccount;
Then, use that custom hooks in your component as usual.
1// file: App.js 2... 3import useAccount from "stores/account"; 4 5function App() { 6 const { 7 account, 8 updateAccount, 9 destroyAccount, 10 loading, 11 error 12 } = useAccount(); 13 14 const onLogout = async () => { 15 await destroyAccount() 16 // your very logic 17 } 18 19 if (loading) { 20 return <div>Loading...</div>; 21 } 22 23 if (error) { 24 return <div>An Error occured</div>; 25 } 26 27 return ( 28 <div> 29 <p>Account Detail: {JSON.stringify(account)}</p> 30 <button onClick={onLogout}>Logout</button> 31 {/* your very component to update account */} 32 </div> 33 ); 34} 35 36export default App;
You can see live demo here
useState
as usual.Redux
or Context API
alternative.SWR
, but you have no idea how to manage synchronous global state with SWR
on client-side.Redux
or Context API
, but you are overwhelmed with their flow.Redux
, how about asynchronous state management like redux-saga
, redux-thunk
, or redux-promise
?At this point, swr-global-state
is based and depends on SWR. After version >2
or later, swr-global-state
now can handle async state too. Just wraps your very async state logic into a function like in Custom Hooks or Asynchronous Persistor.
So, you basically don't need to use Redux
or Context API
anymore. Alternatively, you can choose TanStack Query or default SWR itself.
Since SWR itself supports React Native, of course swr-global-state
supports it too. This example is using Async Storage
in React Native.
Things to note, you must install swr-global-state
version >2
or later, because it has customizable persistor
. So, you can customize the persistor
with React Native Async Storage
.
Under version <2
, swr-global-state
still use localStorage
and we can't customize it. So, it doesn't support React Native.
version
in package.json
is changed to newest version. Then run npm install
for synchronize it to package-lock.json
main
, you can publish the packages by creating new Relase here: https://github.com/gadingnst/swr-global-state/releases/newtag
, make sure the tag
name is same as the version
in package.json
.Publish Release
button, then wait the package to be published.swr-global-state
is freely distributable under the terms of the MIT license.
Feel free to open issues if you found any feedback or issues on swr-global-state
. And feel free if you want to contribute too! 😄
Built with ❤️ by Sutan Gading Fadhillah Nasution on 2022
No vulnerabilities found.
No security vulnerabilities found.