@himanshu-sorathiya/react-kit 1.0.26 → 1.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/storage.d.ts CHANGED
@@ -1,42 +1,299 @@
1
1
  // Generated by dts-bundle-generator v9.5.1
2
2
 
3
+ /**
4
+ * Defines how a value of type `T` is converted to and from the string
5
+ * format that `localStorage`/`sessionStorage` can actually store — the Web
6
+ * Storage API only ever stores strings.
7
+ *
8
+ * Implement this to store types the default JSON-based serializer can't
9
+ * round-trip faithfully, e.g. `Map`, `Set`, `Date`, or `bigint` — see
10
+ * `mapSerializer`, `setSerializer`, `dateSerializer`, and
11
+ * `bigIntSerializer` in `serializers.ts` for ready-made ones.
12
+ *
13
+ * @typeParam T - The in-memory value type this serializer handles.
14
+ */
3
15
  export interface StorageSerializer<T> {
16
+ /** Converts an in-memory value into the string that gets stored. */
4
17
  serialize: (value: T) => string;
18
+ /**
19
+ * Converts a stored string back into an in-memory value.
20
+ *
21
+ * @throws If the raw string can't be converted back into `T`. The hook
22
+ * catches this, falls back to `initialValue`, and reports the error —
23
+ * see `onError` on {@link BaseStorageOptions}.
24
+ */
5
25
  deserialize: (raw: string) => T;
6
26
  }
27
+ /**
28
+ * Options shared by `useLocalStorage` and `useSessionStorage`.
29
+ *
30
+ * @typeParam T - The type of value being stored.
31
+ */
7
32
  export interface BaseStorageOptions<T> {
33
+ /**
34
+ * Custom (de)serializer for values that don't round-trip through
35
+ * `JSON.stringify`/`JSON.parse` cleanly.
36
+ *
37
+ * @defaultValue `defaultSerializer` (plain `JSON.stringify`/`JSON.parse`)
38
+ */
8
39
  serializer?: StorageSerializer<T>;
40
+ /**
41
+ * Whether to synchronously read the existing stored value on mount.
42
+ *
43
+ * - `true` (default): `value` reflects storage from the very first
44
+ * render it's allowed to (see the SSR note below).
45
+ * - `false`: `value` starts as `undefined` and only reflects storage
46
+ * once `isHydrated` becomes `true`, one render after mount. Use this
47
+ * if you'd rather render a loading/skeleton state than briefly show a
48
+ * value that might change right after.
49
+ *
50
+ * Either way, on the server — and during the client's hydration render
51
+ * — `value` is always `initialValue`. This option only affects timing
52
+ * on the client, after that point.
53
+ *
54
+ * @defaultValue `true`
55
+ */
9
56
  initializeWithValue?: boolean;
57
+ /**
58
+ * Whether other instances of this hook watching the *same key* in the
59
+ * *same tab* stay in sync with each other. Implemented via a
60
+ * `CustomEvent` dispatched on `window` — the browser's native `storage`
61
+ * event never fires in the tab that made the change, so without this,
62
+ * two components reading the same key in one tab would drift apart.
63
+ *
64
+ * @defaultValue `true`
65
+ */
10
66
  sameInstanceSync?: boolean;
67
+ /**
68
+ * Called whenever the hook hits an unexpected condition: a failed
69
+ * read, a failed write, a failed cross-instance deserialize, or an
70
+ * attempt to change the storage key at runtime. Fires in every
71
+ * environment, including production — use this for telemetry/error
72
+ * reporting.
73
+ *
74
+ * This is *not* a replacement for the dev-only `console.warn` the hook
75
+ * also emits for the same conditions (visible when
76
+ * `process.env.NODE_ENV !== "production"`) — both fire independently.
77
+ */
78
+ onError?: (error: Error) => void;
11
79
  }
80
+ /**
81
+ * Payload carried by the same-tab `CustomEvent` used for
82
+ * {@link BaseStorageOptions.sameInstanceSync}. Internal — not part of the
83
+ * public hook API, but exported so `useStorageEngine.ts` can import it.
84
+ */
12
85
  export interface StorageCustomEventDetail {
86
+ /** The new serialized value, or `null` if the key was removed. */
13
87
  value: string | null;
88
+ /**
89
+ * A per-hook-instance identifier, used so an instance can recognize —
90
+ * and ignore — the event it just dispatched itself.
91
+ */
14
92
  instanceId: symbol;
15
93
  }
16
- export interface UseLocalStorageOptions<T> extends BaseStorageOptions<T> {
17
- crossInstanceSync?: boolean;
18
- }
19
- export interface UseLocalStorageReturn<T> {
94
+ /**
95
+ * The shape returned by {@link useStorageEngine} — and, re-exported, by
96
+ * both `useLocalStorage` and `useSessionStorage`.
97
+ *
98
+ * @typeParam T - The type of value being stored.
99
+ */
100
+ interface UseStorageEngineReturn<T> {
101
+ /**
102
+ * The current value.
103
+ *
104
+ * - `undefined` if nothing is stored yet and no `initialValue` was
105
+ * given, or — when `initializeWithValue: false` — before hydration
106
+ * completes.
107
+ * - On the server, and during the client's hydration render, this is
108
+ * always `initialValue`: real storage can only be read client-side,
109
+ * and reading it any earlier would produce a hydration mismatch.
110
+ */
20
111
  value: T | undefined;
112
+ /**
113
+ * Writes a new value to storage. Accepts either the value directly, or
114
+ * an updater function that receives the current value and returns the
115
+ * next one — the same convention as `useState`'s setter.
116
+ *
117
+ * A no-op if storage isn't available (SSR, or storage access blocked).
118
+ */
21
119
  setValue: (valueOrUpdater: T | ((prev: T | undefined) => T)) => void;
120
+ /**
121
+ * Removes the key from storage entirely and resets `value` back to
122
+ * whatever `initialValue` was passed to the hook.
123
+ *
124
+ * A no-op if storage isn't available (SSR, or storage access blocked).
125
+ */
22
126
  removeValue: () => void;
127
+ /**
128
+ * `true` once the client has mounted and the hook has settled on its
129
+ * real (non-server-snapshot) value. Useful for showing a loading state
130
+ * instead of a value that might change the instant hydration finishes.
131
+ */
23
132
  isHydrated: boolean;
133
+ /**
134
+ * The most recent error the hook encountered — a failed read, write,
135
+ * or cross-instance sync, or an attempted key change — or `null` if
136
+ * nothing has gone wrong (or an error was cleared by a subsequent
137
+ * successful write/remove). See `onError` on {@link BaseStorageOptions}
138
+ * for an imperative alternative to reading this reactively.
139
+ */
24
140
  error: Error | null;
25
141
  }
26
- export declare function useLocalStorage<T = unknown>(key: string, initialValue?: T, options?: UseLocalStorageOptions<T>): UseLocalStorageReturn<T>;
27
- export type UseSessionStorageOptions<T> = BaseStorageOptions<T>;
28
- export interface UseSessionStorageReturn<T> {
29
- value: T | undefined;
30
- setValue: (valueOrUpdater: T | ((prev: T | undefined) => T)) => void;
31
- removeValue: () => void;
32
- isHydrated: boolean;
33
- error: Error | null;
142
+ /**
143
+ * Options accepted by `useLocalStorage`.
144
+ *
145
+ * @typeParam T - The type of value being stored.
146
+ */
147
+ export interface UseLocalStorageOptions<T> extends BaseStorageOptions<T> {
148
+ /**
149
+ * Whether this hook instance should sync with the same key changing in
150
+ * *other tabs/windows* on the same origin, via the browser's native
151
+ * `storage` event. Has no `sessionStorage` equivalent — sessionStorage
152
+ * isn't shared across tabs, so there's nothing to sync in that case.
153
+ *
154
+ * @defaultValue `true`
155
+ */
156
+ crossInstanceSync?: boolean;
34
157
  }
35
- export declare function useSessionStorage<T = unknown>(key: string, initialValue?: T, options?: UseSessionStorageOptions<T>): UseSessionStorageReturn<T>;
158
+ /**
159
+ * Reads and writes a `localStorage` key, kept in sync with React state.
160
+ *
161
+ * - Persists across page reloads and browser restarts (unlike
162
+ * `useSessionStorage`).
163
+ * - Stays in sync with every component in the current tab watching the
164
+ * same key — see {@link UseLocalStorageOptions.sameInstanceSync} — and
165
+ * with other tabs/windows on the same origin — see
166
+ * {@link UseLocalStorageOptions.crossInstanceSync}.
167
+ * - Safe under SSR: on the server, and during the client's hydration
168
+ * render, `value` is always `initialValue`. The real stored value is
169
+ * only read client-side, immediately after hydration.
170
+ *
171
+ * @typeParam T - The type of value being stored. Defaults to `unknown` if
172
+ * omitted — pass an explicit type argument for anything beyond ad-hoc use.
173
+ * @param key - The `localStorage` key to read and write. Changing this on
174
+ * a later render isn't supported; the hook warns (dev console + `onError`)
175
+ * and keeps using the original key if you do.
176
+ * @param initialValue - Used when nothing is stored yet, as the value
177
+ * shown before hydration completes, and as what `removeValue` resets to.
178
+ * @param options - See {@link UseLocalStorageOptions}.
179
+ * @returns `{ value, setValue, removeValue, isHydrated, error }`.
180
+ *
181
+ * @example
182
+ * Basic usage:
183
+ * ```tsx
184
+ * const { value: theme, setValue: setTheme } = useLocalStorage<"light" | "dark">("theme", "light");
185
+ *
186
+ * <button onClick={() => setTheme(prev => (prev === "light" ? "dark" : "light"))}>
187
+ * Toggle theme
188
+ * </button>
189
+ * ```
190
+ *
191
+ * @example
192
+ * With a custom serializer and error reporting:
193
+ * ```tsx
194
+ * const { value, setValue, error } = useLocalStorage("lastSeen", new Date(), {
195
+ * serializer: dateSerializer,
196
+ * onError: (err) => reportToErrorTracker(err),
197
+ * });
198
+ * ```
199
+ */
200
+ export declare function useLocalStorage<T = unknown>(key: string, initialValue?: T, options?: UseLocalStorageOptions<T>): UseStorageEngineReturn<T>;
201
+ /**
202
+ * Options accepted by `useSessionStorage`. Identical to
203
+ * `BaseStorageOptions` — unlike `UseLocalStorageOptions`, there's no
204
+ * `crossInstanceSync` option here, since sessionStorage isn't shared
205
+ * across tabs in the first place.
206
+ *
207
+ * @typeParam T - The type of value being stored.
208
+ */
209
+ export type UseSessionStorageOptions<T> = BaseStorageOptions<T>;
210
+ /**
211
+ * Reads and writes a `sessionStorage` key, kept in sync with React state.
212
+ *
213
+ * - Scoped to the current tab: cleared when the tab closes, and not
214
+ * shared with other tabs (unlike `useLocalStorage`).
215
+ * - Stays in sync with every component in the current tab watching the
216
+ * same key — see {@link UseSessionStorageOptions.sameInstanceSync}.
217
+ * - Safe under SSR: on the server, and during the client's hydration
218
+ * render, `value` is always `initialValue`. The real stored value is
219
+ * only read client-side, immediately after hydration.
220
+ *
221
+ * @typeParam T - The type of value being stored. Defaults to `unknown` if
222
+ * omitted — pass an explicit type argument for anything beyond ad-hoc use.
223
+ * @param key - The `sessionStorage` key to read and write. Changing this
224
+ * on a later render isn't supported; the hook warns (dev console +
225
+ * `onError`) and keeps using the original key if you do.
226
+ * @param initialValue - Used when nothing is stored yet, as the value
227
+ * shown before hydration completes, and as what `removeValue` resets to.
228
+ * @param options - See {@link UseSessionStorageOptions}.
229
+ * @returns `{ value, setValue, removeValue, isHydrated, error }`.
230
+ *
231
+ * @example
232
+ * ```tsx
233
+ * const { value: draft, setValue: setDraft } = useSessionStorage("draft-comment", "");
234
+ *
235
+ * <textarea value={draft ?? ""} onChange={(e) => setDraft(e.target.value)} />
236
+ * ```
237
+ */
238
+ export declare function useSessionStorage<T = unknown>(key: string, initialValue?: T, options?: UseSessionStorageOptions<T>): UseStorageEngineReturn<T>;
239
+ /**
240
+ * The default serializer used when no `serializer` option is passed to
241
+ * `useLocalStorage`/`useSessionStorage`. Plain `JSON.stringify`/
242
+ * `JSON.parse` — works for any JSON-safe value (objects, arrays, strings,
243
+ * numbers, booleans, `null`), but not `Map`, `Set`, `Date`, `bigint`, or
244
+ * `undefined` (see the other serializers below for those).
245
+ */
36
246
  export declare const defaultSerializer: StorageSerializer<unknown>;
247
+ /**
248
+ * Serializer for `Map` values. `JSON.stringify` can't handle `Map`
249
+ * directly, so this round-trips it via an array of `[key, value]` entries.
250
+ *
251
+ * @typeParam K - The map's key type.
252
+ * @typeParam V - The map's value type.
253
+ *
254
+ * @example
255
+ * ```ts
256
+ * useLocalStorage("tags", new Map<string, number>(), {
257
+ * serializer: mapSerializer<string, number>(),
258
+ * });
259
+ * ```
260
+ */
37
261
  export declare function mapSerializer<K, V>(): StorageSerializer<Map<K, V>>;
262
+ /**
263
+ * Serializer for `Set` values, round-tripped via a plain array.
264
+ *
265
+ * @typeParam V - The set's value type.
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * useLocalStorage("selectedIds", new Set<string>(), {
270
+ * serializer: setSerializer<string>(),
271
+ * });
272
+ * ```
273
+ */
38
274
  export declare function setSerializer<V>(): StorageSerializer<Set<V>>;
275
+ /**
276
+ * Serializer for `Date` values, stored as an ISO 8601 string
277
+ * (`Date.prototype.toISOString`).
278
+ *
279
+ * @throws During `deserialize`, if the stored string isn't a valid date —
280
+ * caught by the hook, which falls back to `initialValue` and reports the
281
+ * error via `onError`/the dev console warning.
282
+ */
39
283
  export declare const dateSerializer: StorageSerializer<Date>;
284
+ /**
285
+ * Serializer for `bigint` values. `JSON.stringify` throws on `bigint`
286
+ * values, so this stores them as a plain decimal string instead.
287
+ *
288
+ * @throws During `deserialize`, if the stored string can't be converted to
289
+ * a `bigint` — caught by the hook, which falls back to `initialValue` and
290
+ * reports the error via `onError`/the dev console warning.
291
+ */
40
292
  export declare const bigIntSerializer: StorageSerializer<bigint>;
41
293
 
294
+ export {
295
+ UseStorageEngineReturn as UseLocalStorageReturn,
296
+ UseStorageEngineReturn as UseSessionStorageReturn,
297
+ };
298
+
42
299
  export {};