Skip to content

Commit 933c240

Browse files
committed
update readme
1 parent 8c1f73e commit 933c240

File tree

3 files changed

+64
-9
lines changed

3 files changed

+64
-9
lines changed

.changeset/cool-stingrays-work.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"persist-and-sync": minor
3+
---
4+
5+
Add ability to change options at Runtime & add clearItem method

README.md

+53-5
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
- ✅ Share state between multiple browsing contexts
1414
- ✅ Additional control over which fields to `persist-and-sync` and which to ignore
1515
- ✅ Optimized for performance using memoization and closures.
16+
- ✅ Update options at runtime by setting `__persistNSyncOptions` in your store.
1617

1718
## Install
1819

@@ -60,7 +61,9 @@ const useStore = create<MyStore>(
6061

6162
## Advanced Usage (Customizations)
6263

63-
In several cases you might want to exclude several fields from syncing. To support this scenario, we provide a mechanism to exclude fields based on list of fields or regular expression.
64+
### PersistNSyncOptions
65+
66+
In several cases, you might want to exclude several fields from syncing. To support this scenario, we provide a mechanism to exclude fields based on a list of fields or regular expressions.
6467

6568
```typescript
6669
type PersistNSyncOptionsType = {
@@ -95,13 +98,58 @@ export const useMyStore = create<MyStoreType>()(
9598

9699
> It is good to note here that each element of `include` and `exclude` array can either be a string or a regular expression.
97100
> To use regular expression, you should either use `new RegExp()` or `/your-expression/` syntax. Double or single quoted strings are not treated as regular expression.
98-
> You can specify whether to use either `"localStorage"`, `"sessionStorage"`, or `"cookies"` to persist the state - default `"localStorage"`.
101+
> You can specify whether to use either `"localStorage"`, `"sessionStorage"`, or `"cookies"` to persist the state - default `"localStorage"`. Please note that `"sessionStorage"` is not persisted. Hence can be used for sync only scenarios.
102+
103+
### Updating options at runtime
104+
105+
Since version 1.2, you can also update the options at runTime by setting `__persistNSyncOptions` in your Zustand state.
106+
107+
**Example**
108+
109+
```ts
110+
interface StoreWithOptions {
111+
count: number;
112+
_count: number;
113+
__persistNSyncOptions: PersistNSyncOptionsType;
114+
setCount: (c: number) => void;
115+
set_Count: (c: number) => void;
116+
setOptions: (__persistNSyncOptions: PersistNSyncOptionsType) => void;
117+
}
118+
119+
const defaultOptions = { name: "example", include: [/count/], exclude: [/^_/] };
120+
121+
export const useStoreWithOptions = create<StoreWithOptions>(
122+
persistNSync(
123+
set => ({
124+
count: 0,
125+
_count: 0 /** skipped as it matches the regexp provided */,
126+
__persistNSyncOptions: defaultOptions,
127+
setCount: count => set(state => ({ ...state, count })),
128+
set_Count: _count => set(state => ({ ...state, _count })),
129+
setOptions: __persistNSyncOptions => set(state => ({ ...state, __persistNSyncOptions })),
130+
}),
131+
defaultOptions,
132+
),
133+
);
134+
```
135+
136+
### Clear Storage
137+
138+
Starting from version 1.2, you can also clear the persisted data by calling `clearStorage` function. It takes `name` of your store (`name` passed in `options` while creating the store), and optional `storageType` parameters.
139+
140+
```ts
141+
import { clearStorage } from "persist-and-sync";
142+
143+
...
144+
clearStorage("my-store", "cookies");
145+
...
146+
```
99147

100148
## Legacy / Deprecated
101149

102-
#### Ignore / filter out fields based on regExp
150+
#### Ignore/filter out fields based on regExp
103151

104-
In several cases you might want to exclude several fields from syncing. To support this scenario, we provide a mechanism to exclude fields based on regExp. Just pass `regExpToIgnore` (optional - default -> undefined) in options object.
152+
In several cases, you might want to exclude several fields from syncing. To support this scenario, we provide a mechanism to exclude fields based on regExp. Just pass `regExpToIgnore` (optional - default -> undefined) in the options object.
105153

106154
```ts
107155
// to ignore fields containing a slug
@@ -122,7 +170,7 @@ For more details about regExp check out - [JS RegExp](https://www.w3schools.com/
122170

123171
### Exact match
124172

125-
For exactly matching a parameter/field use `/^your-field-name$/`. `^` forces match from the first caracter and similarly, `$` forces match until the last character.
173+
For exactly matching a parameter/field use `/^your-field-name$/`. `^` forces match from the first character and similarly, `$` forces match until the last character.
126174

127175
### Ignore multiple fields with exact match
128176

packages/persist-and-sync/src/index.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ function setItem(options: PersistNSyncOptionsType, value: string) {
3939
else localStorage.setItem(options.name, value);
4040
}
4141

42-
export function clearItem(name: string, storage?: StorageType) {
42+
export function clearStorage(name: string, storage?: StorageType) {
4343
switch (storage || "localStorage") {
4444
case "localStorage":
4545
localStorage.removeItem(name);
@@ -125,7 +125,7 @@ function saveAndSync({ newState, prevState, options }: SaveAndSyncProps) {
125125
const newStorage = newState.__persistNSyncOptions?.storage || options.storage;
126126
if (prevStorage !== newStorage) {
127127
const name = prevState.__persistNSyncOptions.name || options.name;
128-
clearItem(name, prevStorage);
128+
clearStorage(name, prevStorage);
129129
}
130130
Object.assign(options, newState.__persistNSyncOptions);
131131
}
@@ -140,6 +140,8 @@ function saveAndSync({ newState, prevState, options }: SaveAndSyncProps) {
140140
if (keysToPersistAndSync.length === 0) return;
141141

142142
const stateToStore: Record<string, any> = {};
143-
keysToPersistAndSync.forEach(key => (stateToStore[key] = newState[key]));
144-
setItem(options, JSON.stringify(stateToStore));
143+
keysToPersistAndSync
144+
.filter(key => prevState[key] !== newState[key]) // using only shallow equality
145+
.forEach(key => (stateToStore[key] = newState[key]));
146+
if (Object.keys(stateToStore).length) setItem(options, JSON.stringify(stateToStore));
145147
}

0 commit comments

Comments
 (0)