Skip to content

Commit

Permalink
chore: 修改usePageCacheState示例
Browse files Browse the repository at this point in the history
  • Loading branch information
bbb169 committed Sep 11, 2024
1 parent 03b70b0 commit 76b322d
Show file tree
Hide file tree
Showing 8 changed files with 53 additions and 58 deletions.
1 change: 1 addition & 0 deletions config/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export const menus = [
'useCookieState',
'useLocalStorageState',
'useSessionStorageState',
'usePageCacheState',
'useDebounce',
'useThrottle',
'useMap',
Expand Down
8 changes: 5 additions & 3 deletions packages/hooks/src/usePageCacheState/demo/demo1.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
*/

import React from 'react';
import { useLocalStorageState } from 'ahooks';
import usePageCacheState from '..';

export default function () {
const [message, setMessage] = useLocalStorageState<string | undefined>(
const [message, setMessage] = usePageCacheState<string | undefined>(
'use-local-storage-state-demo1',
{
defaultValue: 'Hello~',
useStorageStateOptions: {
defaultValue: 'Hello~',
},
},
);

Expand Down
10 changes: 6 additions & 4 deletions packages/hooks/src/usePageCacheState/demo/demo2.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
*/

import React from 'react';
import { useLocalStorageState } from 'ahooks';
import usePageCacheState from '..';

const defaultArray = ['a', 'e', 'i', 'o', 'u'];

export default function () {
const [value, setValue] = useLocalStorageState('use-local-storage-state-demo2', {
defaultValue: defaultArray,
const [value, setValue] = usePageCacheState('use-local-storage-state-demo2', {
useStorageStateOptions: {
defaultValue: defaultArray,
},
});

return (
Expand All @@ -22,7 +24,7 @@ export default function () {
<button
type="button"
style={{ marginRight: '16px' }}
onClick={() => setValue([...value, Math.random().toString(36).slice(-1)])}
onClick={() => setValue([...(value || []), Math.random().toString(36).slice(-1)])}
>
push random
</button>
Expand Down
11 changes: 7 additions & 4 deletions packages/hooks/src/usePageCacheState/demo/demo3.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,17 @@

import React from 'react';
import { useLocalStorageState } from 'ahooks';
import usePageCacheState from '..';

export default function () {
const [message, setMessage] = useLocalStorageState<string | undefined>(
const [message, setMessage] = usePageCacheState<string | undefined>(
'use-local-storage-state-demo3',
{
defaultValue: 'Hello~',
serializer: (v) => v ?? '',
deserializer: (v) => v,
useStorageStateOptions: {
defaultValue: 'Hello~',
serializer: (v) => v ?? '',
deserializer: (v) => v,
},
},
);

Expand Down
10 changes: 6 additions & 4 deletions packages/hooks/src/usePageCacheState/demo/demo4.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import React from 'react';
import { useLocalStorageState } from 'ahooks';
import usePageCacheState from '..';

export default function () {
return (
Expand All @@ -19,9 +19,11 @@ export default function () {
}

function Counter() {
const [count, setCount] = useLocalStorageState('use-local-storage-state-demo4', {
defaultValue: 0,
listenStorageChange: true,
const [count, setCount] = usePageCacheState('use-local-storage-state-demo4', {
useStorageStateOptions: {
defaultValue: 0,
listenStorageChange: true,
},
});

return (
Expand Down
20 changes: 10 additions & 10 deletions packages/hooks/src/usePageCacheState/index.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ nav:
path: /hooks
---

# useLocalStorageState
# usePageCacheState

A Hook that store state into localStorage.

Expand Down Expand Up @@ -39,7 +39,7 @@ interface Options<T> {
onError?: (error: unknown) => void;
}

const [state, setState] = useLocalStorageState<T>(
const [state, setState] = usePageCacheState<T>(
key: string,
options: Options<T>
): [T?, (value?: SetState<T>) => void];
Expand All @@ -54,14 +54,14 @@ const [state, setState] = useLocalStorageState<T>(
### Options
| Property | Description | Type | Default |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | ----------------------------- |
| defaultValue | Default value | `any \| (() => any)` | - |
| listenStorageChange | Whether to listen storage changes. If `true`, when the stored value changes, all `useLocalStorageState` with the same `key` will synchronize their states, including different tabs of the same browser | `boolean` | `false` |
| serializer | Custom serialization method | `(value: any) => string` | `JSON.stringify` |
| deserializer | Custom deserialization method | `(value: string) => any` | `JSON.parse` |
| onError | On error callback | `(error: unknown) => void` | `(e) => { console.error(e) }` |
| Property | Description | Type | Default |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | ----------------------------- |
| defaultValue | Default value | `any \| (() => any)` | - |
| listenStorageChange | Whether to listen storage changes. If `true`, when the stored value changes, all `usePageCacheState` with the same `key` will synchronize their states, including different tabs of the same browser | `boolean` | `false` |
| serializer | Custom serialization method | `(value: any) => string` | `JSON.stringify` |
| deserializer | Custom deserialization method | `(value: string) => any` | `JSON.parse` |
| onError | On error callback | `(error: unknown) => void` | `(e) => { console.error(e) }` |
## Remark
useLocalStorageState will call `serializer` before write data to localStorage, and call `deserializer` once after read data.
usePageCacheState will call `serializer` before write data to localStorage, and call `deserializer` once after read data.
31 changes: 8 additions & 23 deletions packages/hooks/src/usePageCacheState/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,23 +41,7 @@ interface Options<T> {

type StorageStateRecorder<T> = Record<string, Record<string, UnitStorageState<T>>>;

export default function <T>(
key: string,
options?: Options<T>,
): [
unitData: T | undefined,
(unitData: SetUnitDataState<T>) => void,
{
delete: (subKey?: string | undefined) => void;
storageStateRecorder: StorageStateRecorder<T> | undefined;
setStorageStateRecorder: (
value?:
| StorageStateRecorder<T>
| SetStateAction<StorageStateRecorder<T> | undefined>
| undefined,
) => void;
},
] {
export default function <T>(key: string, options?: Options<T>) {
useEffect(() => {
if ([options?.version, options?.subKey].includes('default')) {
console.warn(
Expand All @@ -73,6 +57,7 @@ export default function <T>(
expire = 1000 * 60 * 60 * 24 * 180,
expireTimeProp = 'updateTime',
timeFormat = 'YYYY-MM-DD HH-mm-ss',
storageType = 'localStorage',
} = options || {};

const getRealityStorageKey = (
Expand All @@ -92,9 +77,9 @@ export default function <T>(
);
const getStorage = useCallback(() => {
if (isBrowser) {
if (options?.storageType === 'sessionStorage') {
if (storageType === 'sessionStorage') {
return sessionStorage;
} else if (options?.storageType === 'localStorage') {
} else if (storageType === 'localStorage') {
return localStorage;
}
}
Expand Down Expand Up @@ -149,8 +134,8 @@ export default function <T>(

const handlePreKeyRecorder = (preKeyRecorder: any) => {
const finalDataStateRecord: UnitStorageState<T> = {
...curKeyStorageRecorder?.[subKey][version],
...(curKeyStorageRecorder?.[subKey][version]
...curKeyStorageRecorder?.[subKey]?.[version],
...(curKeyStorageRecorder?.[subKey]?.[version]
? {}
: {
createTime: curTime,
Expand Down Expand Up @@ -188,7 +173,7 @@ export default function <T>(

setPageCacheKeysRecorder(newPageCacheKeysRecorder);
}
});
}, [pageCache]);

const deleteStorageBySubKey = useMemoizedFn((deleteSubKey) => {
setPageCache(undefined);
Expand All @@ -210,5 +195,5 @@ export default function <T>(
storageStateRecorder: pageCacheKeysRecorder,
setStorageStateRecorder: setPageCacheKeysRecorder,
},
];
] as const;
}
20 changes: 10 additions & 10 deletions packages/hooks/src/usePageCacheState/index.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ nav:
path: /hooks
---

# useLocalStorageState
# usePageCacheState

将状态存储在 localStorage 中的 Hook 。

Expand Down Expand Up @@ -39,7 +39,7 @@ interface Options<T> {
onError?: (error: unknown) => void;
}

const [state, setState] = useLocalStorageState<T>(
const [state, setState] = usePageCacheState<T>(
key: string,
options: Options<T>
): [T?, (value?: SetState<T>) => void];
Expand All @@ -54,14 +54,14 @@ const [state, setState] = useLocalStorageState<T>(
### Options
| 参数 | 说明 | 类型 | 默认值 |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | ----------------------------- |
| defaultValue | 默认值 | `any \| (() => any)` | - |
| listenStorageChange | 是否监听存储变化。如果是 `true`,当存储值变化时,所有 `key` 相同的 `useLocalStorageState` 会同步状态,包括同一浏览器不同 tab 之间 | `boolean` | `false` |
| serializer | 自定义序列化方法 | `(value: any) => string` | `JSON.stringify` |
| deserializer | 自定义反序列化方法 | `(value: string) => any` | `JSON.parse` |
| onError | 错误回调函数 | `(error: unknown) => void` | `(e) => { console.error(e) }` |
| 参数 | 说明 | 类型 | 默认值 |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------- | ----------------------------- |
| defaultValue | 默认值 | `any \| (() => any)` | - |
| listenStorageChange | 是否监听存储变化。如果是 `true`,当存储值变化时,所有 `key` 相同的 `usePageCacheState` 会同步状态,包括同一浏览器不同 tab 之间 | `boolean` | `false` |
| serializer | 自定义序列化方法 | `(value: any) => string` | `JSON.stringify` |
| deserializer | 自定义反序列化方法 | `(value: string) => any` | `JSON.parse` |
| onError | 错误回调函数 | `(error: unknown) => void` | `(e) => { console.error(e) }` |
## 备注
useLocalStorageState 在往 localStorage 写入数据前,会先调用一次 `serializer`,在读取数据之后,会先调用一次 `deserializer`
usePageCacheState 在往 localStorage 写入数据前,会先调用一次 `serializer`,在读取数据之后,会先调用一次 `deserializer`

0 comments on commit 76b322d

Please sign in to comment.