@emab/react-state-sync
v0.1.7
Published
  ;You can provide a State type which will be used to type the value returned by the hook:
type State = {
count: number;
};
const [value, syncValue, updateValueOptimistically] = useSyncedState<State>("count", 0);Parameters:
stateKey(string): A unique key that identifies the state to be synced across multiple tabs or windows.initialValue(T): The initial value for the state.options: (Options): An optional object containing options for the hook.
Return Values:
value(T): The current state value.syncValue(TVoidFunction): Function to sync the state. This will also broadcast the new state to other tabs/windows.updateValueOptimistically(TOptimisticUpdateFunction): Function that updates the state optimistically, returning an object withrollbackValueandsyncValuefunctions.
Using syncValue:
To update the state value and broadcast the new state to other tabs/windows, call syncValue:
syncValue(newValue);Using updateValueOptimistically:
To perform an optimistic update, call updateValueOptimistically:
const {rollbackValue, syncValue} = updateValueOptimistically(newValue);This function will immediately update the state and return two functions:
rollbackValue: Call this function if you want to roll back the state to the value it had before the optimistic update.syncValue: Call this function when you're sure you want to commit the optimistic update. You can optionally pass a new value to sync.
For example:
const handleOptimisticUpdate = async (newValue) => {
const {rollbackValue, syncValue} = updateValueOptimistically(newValue);
try {
// Replace this with your actual API request or some operation that could fail
await fakeApiRequest();
syncValue(); // sync the new value across tabs
} catch (error) {
rollbackValue(); // rollback to the old value in case of failure
}
};You can also provide a new value to syncValue once the response is complete:
const handleOptimisticUpdate = async (newValue) => {
const {rollbackValue, syncValue} = updateValueOptimistically(newValue);
try {
// Replace this with your actual API request or some operation that could fail
const response = await fakeApiRequest();
syncValue(response.data); // sync the new value across tabs
} catch (error) {
rollbackValue(); // rollback to the old value in case of failure
}
};Options
The useSyncedState hook accepts an optional Options object as its third parameter. The following options are available:
syncOnMount(boolean): Whether to sync the initial value on mount. Defaults tofalse.
Compatibility
This hook requires a browser environment that supports the BroadcastChannel API. Make sure to check its compatibility if you're targeting older browsers.
License
This project is open sourced under the MIT License.
Contribution
Contributions are welcome! Please open an issue if you find a bug or have a feature request. You can also propose changes via a pull request.
Author
Eddy Brown - GitHub
