Skip to content

Commit

Permalink
chore: 更新英文示例及文档
Browse files Browse the repository at this point in the history
  • Loading branch information
bbb169 committed Sep 23, 2024
1 parent c262210 commit 33d19e8
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 37 deletions.
2 changes: 1 addition & 1 deletion packages/hooks/src/usePageCacheState/demo/demo1.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default function () {
useStorageStateOptions: {
defaultValue: 'Hello~',
},
expire: 10,
storageType: 'sessionStorage',
},
);

Expand Down
32 changes: 29 additions & 3 deletions packages/hooks/src/usePageCacheState/demo/demo3.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
* desc.zh-CN: 对于普通的字符串,可能你不需要默认的 `JSON.stringify/JSON.parse` 来序列化。
*/

import React from 'react';
import { useLocalStorageState } from 'ahooks';
import React, { useState } from 'react';
import usePageCacheState from '..';
import { Select } from 'antd';

export default function () {
const UserDataDisplayer = ({ userId }: { userId: string }) => {
const [message, setMessage] = usePageCacheState<string | undefined>(
'use-local-storage-state-demo3',
{
Expand All @@ -19,6 +19,7 @@ export default function () {
serializer: (v) => v ?? '',
deserializer: (v) => v,
},
subKey: userId,
expire: 10,
},
);
Expand All @@ -38,4 +39,29 @@ export default function () {
</button>
</>
);
};

export default function () {
const [userId, setUserId] = useState<string>('');

return (
<>
<Select
style={{ width: 100 }}
options={[
{
label: 'jack',
value: 'jack',
},
{
label: 'peter',
value: 'peter',
},
]}
value={userId}
onChange={setUserId}
/>
{userId && <UserDataDisplayer userId={userId} />}
</>
);
}
90 changes: 57 additions & 33 deletions packages/hooks/src/usePageCacheState/index.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,63 +5,87 @@ nav:

# usePageCacheState

A Hook that store state into localStorage.
usePageCacheState is a solution for handling page-level caching. It records the complete state of the current page in the cache, which typically involves caching a large amount of data. You can use localStorage or sessionStorage to store the cached data.

## Examples

### Store state into localStorage
### Store state into sessionStorage

<code src="./demo/demo1.tsx" />

### Store complex types of data
### Store temporary data

<code src="./demo/demo2.tsx" />

### Custom serialization and deserialization functions
### Store data for different users

<code src="./demo/demo3.tsx" />

### Sync state with localStorage

<code src="./demo/demo4.tsx" />

## API

If you want to delete this record from localStorage, you can use `setState()` or `setState(undefined)`.
`useStorageStateOptions` is same as the props of `useLocalStorageState` and `useSessionStorageState`, you can just pass those props into `useStorageStateOptions` to get the same performance.

```typescript
type SetState<S> = S | ((prevState?: S) => S);
export type StorageType = 'localStorage' | 'sessionStorage';
export type ExpireTimeProp = 'createTime' | 'updateTime';

/** 单条记录的存储的数据类型 */
type UnitStorageState<T> = {
subKey: Exclude<Options<T>['subKey'], undefined>;
createTime: string;
createTimeFormat: string;
updateTime: string;
updateTimeFormat: string;
/** 用户数据 */
data?: T;
};

export type SetUnitDataState<S> = S | ((prevState?: S) => S);

interface Options<T> {
defaultValue?: T | (() => T);
serializer?: (value: T) => string;
deserializer?: (value: string) => T;
onError?: (error: unknown) => void;
/** 缓存类型 */
storageType?: StorageType;
/** 二级key。用于区分同个页面,不同用户的缓存 */
subKey?: string;
/** 过期时间 单位秒 s */
expire?: number;
/** 用于计算过期时间取值属性 */
expireTimeProp?: ExpireTimeProp;
/** 最大数量 */
maxCount?: number;
/** 缓存版本号 */
version?: number | string;
timeFormat?: string;
useStorageStateOptions?: UseStorageStateOption<T>;
}

const [state, setState] = usePageCacheState<T>(
key: string,
options: Options<T>
): [T?, (value?: SetState<T>) => void];
type StorageStateRecorder<T> = Record<string, Record<string, UnitStorageState<T>>>;


const [state, setState] = usePageCacheState<T>(key: string, options?: Options<T>): [T | undefined, (value?: SetState<T> | undefined) => void, {
delete: (this: any, deleteSubKey: any) => void;
storageStateRecorder: StorageStateRecorder<...> | undefined;
setStorageStateRecorder: (value?: SetState<...> | undefined) => void;
}];
```
### Result
| Property | Description | Type |
| -------- | --------------------------- | ------------------------------- |
| state | Local `localStorage` value | `T` |
| setState | Update `localStorage` value | `(value?: SetState<T>) => void` |
| Property | Description | Type |
| ------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| state | storaged value | `T` |
| setState | Update storaged value | `(value?: SetState<T>) => void` |
| operateStates | operation all storaged value's recorder | `{ delete: (this: any, deleteSubKey: any) => void; storageStateRecorder: StorageStateRecorder<...> \| undefined; setStorageStateRecorder: (value?: SetState<...> \| undefined) => void; }` |
### Options
| 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
usePageCacheState will call `serializer` before write data to localStorage, and call `deserializer` once after read data.
| Property | Description | Type | Default |
| ---------------------- | -------------------------------------------------------------------------------- | ------------------------------------ | --------------------------- |
| storageType | type of storage data value | `'localStorage' \| 'sessionStorage'` | `'localStorage'` |
| subKey | Secondary key. Used to differentiate cache for different users on the same page. | `string` | `default` |
| expire | Expiration time in seconds (s)method | `number` | `1000 * 60 * 60 * 24 * 180` |
| expireTimeProp | Property used to calculate the expiration time | `string` | `'updateTime'` |
| maxCount | Maximum number of items to store | `number` | `100` |
| version | Cache version number | `number \| string` | `'default'` |
| timeFormat | Format for time representation | `string` | `'YYYY-MM-DD HH:mm:ss'` |
| useStorageStateOptions | same as the props of `useLocalStorageState` and `useSessionStorageState` | `UseStorageStateOption<T>` | - |

0 comments on commit 33d19e8

Please sign in to comment.