This script uses broadcast-channel and zustand 's PersistStorage
to create a persist storage that communicates with the browser's other tabs to keep the state up-to-date.
While another tab exists, the new tabs get their initial state from the existing one (i,e from the leader tab).
It has been tested with a for
loop to easily handle more than 100 communications across multiple tabs, in Chrome and Firefox for Windows and Android.
Known issue: For older versions of Firefox Android which don't support BroadcastChannel
, it uses localStorage
and new tabs don't get the initial state from the other ones.
-
Install
zustand
andbroadcast-channel
-
Copy the file
storage1.ts
somewhere inside your project (such asstore/cart.ts
)
You can also make more copies for extra storages such asstore/chat.ts
,store/token.ts
, etc -
Customize its related parts (especially
name
,valInit
andvalType
)
- Import the file(s) anywhere into your script(s):
import { useStoreGet, useStoreSet } from "./store/cart.ts"
// Or if you have multiple storages:
import * as cart from "./store/cart.ts"
- Get a value from inside any hook/component and make it render the hook/component after every related state update:
const data = useStoreGet()
// Or:
const data = cart.useStoreGet()
return <div>Cart data is: {data}</div>
- Set a value from inside any hook/component without rendering it:
const [setVal, reset, increase, decrease] = useStoreSet()
// Or:
const [setVal, reset, increase, decrease] = cart.useStoreSet()
// To use only the main setter:
const [setVal] = useStoreSet()
// Or:
const [setVal] = cart.useStoreSet()
return <button onClick={() => setVal(parseInt(prompt("Enter new value:")))}>Enter</button>
You can also use a setter function, again without rendering the parent hook/component:
return <button onClick={() => setVal((prev) => prev + 5)}>Increase by 5</button>