Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add useIndexDBState hook #2740

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions packages/hooks/src/useIndexDBState/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# useIndexDBState

A React Hook that stores state into IndexedDB.

## Examples

### Basic usage

```jsx
import React from 'react';
import { useIndexDBState } from 'ahooks';

export default function Demo() {
const [message, setMessage] = useIndexDBState('message', {
defaultValue: 'Hello',
});

return (
<>
<input
value={message || ''}
onChange={(e) => setMessage(e.target.value)}
/>
<button onClick={() => setMessage(undefined)}>Reset</button>
</>
);
}
```

### Store complex object

```jsx
import React from 'react';
import { useIndexDBState } from 'ahooks';

export default function Demo() {
const [user, setUser] = useIndexDBState('user', {
defaultValue: { name: 'Ahooks', age: 1 },
});

return (
<>
<pre>{JSON.stringify(user, null, 2)}</pre>
<button
onClick={() => setUser({ name: 'New Name', age: 2 })}
>
Update User
</button>
</>
);
}
```

## API

```typescript
type SetState<S> = S | ((prevState?: S) => S);

interface Options<T> {
defaultValue?: T | (() => T);
dbName?: string;
storeName?: string;
version?: number;
onError?: (error: unknown) => void;
}

const [state, setState] = useIndexDBState<T>(key: string, options?: Options<T>);
```

### Params

| Property | Description | Type | Default |
|----------|-------------|------|---------|
| key | The key of the IndexedDB record | `string` | - |
| options | Optional configuration | `Options` | - |

### Options

| Property | Description | Type | Default |
|----------|-------------|------|---------|
| defaultValue | Default value | `T \| (() => T)` | `undefined` |
| dbName | Name of the IndexedDB database | `string` | `ahooks-indexdb` |
| storeName | Name of the object store | `string` | `ahooks-store` |
| version | Version of the database | `number` | `1` |
| onError | Error handler | `(error: unknown) => void` | `(e) => console.error(e)` |

### Result

| Property | Description | Type |
|----------|-------------|------|
| state | Current state | `T` |
| setState | Set state | `(value?: SetState<T>) => void` |
116 changes: 116 additions & 0 deletions packages/hooks/src/useIndexDBState/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { renderHook, act } from '@testing-library/react';
import useIndexDBState from '../index';

// 模拟 IndexedDB
const mockIndexedDB = {
open: jest.fn(),
};

const mockIDBOpenDBRequest = {
onerror: null,
onsuccess: null,
onupgradeneeded: null,
result: {
transaction: jest.fn(),
close: jest.fn(),
objectStoreNames: {
contains: jest.fn().mockReturnValue(false),
},
createObjectStore: jest.fn(),
},
};

const mockObjectStore = {
get: jest.fn(),
put: jest.fn(),
delete: jest.fn(),
};

const mockTransaction = {
objectStore: jest.fn().mockReturnValue(mockObjectStore),
};

// 模拟 window.indexedDB
Object.defineProperty(window, 'indexedDB', {
value: mockIndexedDB,
writable: true,
});

describe('useIndexDBState', () => {
beforeEach(() => {
// 设置全局 indexedDB 模拟
mockIndexedDB.open.mockReturnValue(mockIDBOpenDBRequest);
mockIDBOpenDBRequest.result.transaction.mockReturnValue(mockTransaction);

// 清除之前的模拟调用
jest.clearAllMocks();
});

it('should initialize with default value', async () => {
const { result } = renderHook(() =>
useIndexDBState('test-key', {
defaultValue: 'default value',
}),
);

expect(result.current[0]).toBe('default value');
});

it('should update state when setState is called', async () => {
const { result } = renderHook(() =>
useIndexDBState('test-key', {
defaultValue: 'default value',
}),
);

act(() => {
result.current[1]('new value');
});

expect(result.current[0]).toBe('new value');
});

it('should handle function updater', async () => {
const { result } = renderHook(() =>
useIndexDBState('test-key', {
defaultValue: 'default value',
}),
);

act(() => {
result.current[1]((prev) => `${prev} updated`);
});

expect(result.current[0]).toBe('default value updated');
});

it('should handle undefined value', async () => {
const { result } = renderHook(() =>
useIndexDBState('test-key', {
defaultValue: 'default value',
}),
);

act(() => {
result.current[1](undefined);
});

expect(result.current[0]).toBeUndefined();
});

it('should call onError when an error occurs', async () => {
const onError = jest.fn();
mockIndexedDB.open.mockImplementationOnce(() => {
throw new Error('Test error');
});

renderHook(() =>
useIndexDBState('test-key', {
defaultValue: 'default value',
onError,
}),
);

expect(onError).toHaveBeenCalled();
});
});
40 changes: 40 additions & 0 deletions packages/hooks/src/useIndexDBState/demo/demo1.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* title: Basic usage
* desc: Persist state into IndexedDB
*
* title.zh-CN: 基础用法
* desc.zh-CN: 将状态持久化存储到 IndexedDB 中
*/

import React from 'react';
import useIndexDBState from '../index';

export default function Demo() {
const [message, setMessage] = useIndexDBState<string>('message', {
defaultValue: 'Hello',
});

return (
<>
<input
value={message || ''}
placeholder="Please enter some text"
onChange={(e) => setMessage(e.target.value)}
style={{ width: 200, marginRight: 16 }}
/>
<button
type="button"
onClick={() => setMessage(undefined)}
style={{ marginRight: 16 }}
>
Reset
</button>
<button
type="button"
onClick={() => window.location.reload()}
>
Refresh
</button>
</>
);
}
76 changes: 76 additions & 0 deletions packages/hooks/src/useIndexDBState/demo/demo2.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* title: Store complex object
* desc: useIndexDBState can store complex objects
*
* title.zh-CN: 存储复杂对象
* desc.zh-CN: useIndexDBState 可以存储复杂对象
*/

import React, { useState } from 'react';
import useIndexDBState from '../index';

interface User {
name: string;
age: number;
}

export default function Demo() {
const [user, setUser] = useIndexDBState<User>('user', {
defaultValue: { name: 'Ahooks', age: 1 },
});

const [inputValue, setInputValue] = useState('');
const [inputAge, setInputAge] = useState('');

return (
<>
<div>
<label>Name: </label>
<input
value={inputValue}
placeholder="Please enter name"
onChange={(e) => setInputValue(e.target.value)}
style={{ width: 200, marginRight: 16 }}
/>
</div>
<div style={{ marginTop: 8 }}>
<label>Age: </label>
<input
value={inputAge}
placeholder="Please enter age"
onChange={(e) => setInputAge(e.target.value)}
style={{ width: 200, marginRight: 16 }}
/>
</div>
<div style={{ marginTop: 16 }}>
<button
type="button"
onClick={() => {
setUser({ name: inputValue, age: Number(inputAge) });
setInputValue('');
setInputAge('');
}}
style={{ marginRight: 16 }}
>
Save
</button>
<button
type="button"
onClick={() => setUser(undefined)}
style={{ marginRight: 16 }}
>
Reset
</button>
<button
type="button"
onClick={() => window.location.reload()}
>
Refresh
</button>
</div>
<div style={{ marginTop: 16 }}>
<pre>{JSON.stringify(user, null, 2)}</pre>
</div>
</>
);
}
58 changes: 58 additions & 0 deletions packages/hooks/src/useIndexDBState/index.en-US.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
---
nav:
path: /hooks
---

# useIndexDBState

A Hook that stores state into IndexedDB.

## Examples

### Basic usage

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

### Complex object

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

## API

```typescript
type SetState<S> = S | ((prevState?: S) => S);

interface Options<T> {
defaultValue?: T | (() => T);
dbName?: string;
storeName?: string;
version?: number;
onError?: (error: unknown) => void;
}

const [state, setState] = useIndexDBState<T>(key: string, options?: Options<T>);
```

### Params

| Property | Description | Type | Default |
|----------|-------------|------|---------|
| key | The key of the IndexedDB record | `string` | - |
| options | Optional configuration | `Options` | - |

### Options

| Property | Description | Type | Default |
|----------|-------------|------|---------|
| defaultValue | Default value | `T \| (() => T)` | `undefined` |
| dbName | Name of the IndexedDB database | `string` | `ahooks-indexdb` |
| storeName | Name of the object store | `string` | `ahooks-store` |
| version | Version of the database | `number` | `1` |
| onError | Error handler | `(error: unknown) => void` | `(e) => console.error(e)` |

### Result

| Property | Description | Type |
|----------|-------------|------|
| state | Current state | `T` |
| setState | Set state | `(value?: SetState<T>) => void` |
Loading