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 useProState hook #2520

Open
wants to merge 15 commits into
base: v4
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 13 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
122 changes: 122 additions & 0 deletions config/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
export const menus = [
{
title: 'useRequest',
children: [
'useRequest/doc/index',
'useRequest/doc/basic',
'useRequest/doc/loadingDelay',
'useRequest/doc/polling',
'useRequest/doc/ready',
'useRequest/doc/refreshDeps',
'useRequest/doc/refreshOnWindowFocus',
'useRequest/doc/debounce',
'useRequest/doc/throttle',
'useRequest/doc/cache',
'useRequest/doc/retry',
],
},
{
title: 'Scene',
children: [
'useAntdTable',
'useFusionTable',
'useInfiniteScroll',
'usePagination',
'useDynamicList',
'useVirtualList',
'useHistoryTravel',
'useNetwork',
'useSelections',
'useCountDown',
'useCounter',
'useTextSelection',
'useWebSocket',
],
},
{
title: 'LifeCycle',
children: ['useMount', 'useUnmount', 'useUnmountedRef'],
},
{
title: 'State',
children: [
'useProState',
'useSetState',
'useBoolean',
'useToggle',
'use-url-state',
'useCookieState',
'useLocalStorageState',
'useSessionStorageState',
'useDebounce',
'useThrottle',
'useMap',
'useSet',
'usePrevious',
'useRafState',
'useSafeState',
'useGetState',
'useResetState',
],
},
{
title: 'Effect',
children: [
'useUpdateEffect',
'useUpdateLayoutEffect',
'useAsyncEffect',
'useDebounceEffect',
'useDebounceFn',
'useThrottleFn',
'useThrottleEffect',
'useDeepCompareEffect',
'useDeepCompareLayoutEffect',
'useInterval',
'useRafInterval',
'useTimeout',
'useRafTimeout',
'useLockFn',
'useUpdate',
],
},
{
title: 'Dom',
children: [
'useEventListener',
'useClickAway',
'useDocumentVisibility',
'useDrop',
'useEventTarget',
'useExternal',
'useTitle',
'useFavicon',
'useFullscreen',
'useHover',
'useMutationObserver',
'useInViewport',
'useKeyPress',
'useLongPress',
'useMouse',
'useResponsive',
'useScroll',
'useSize',
'useFocusWithin',
],
},
{
title: 'Advanced',
children: [
'useControllableValue',
'useCreation',
'useEventEmitter',
'useIsomorphicLayoutEffect',
'useLatest',
'useMemoizedFn',
'useReactive',
],
},
{
title: 'Dev',
children: ['useTrackedEffect', 'useWhyDidYouUpdate'],
},
coding-ice marked this conversation as resolved.
Show resolved Hide resolved
];
8 changes: 5 additions & 3 deletions packages/hooks/src/useExternal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@ const EXTERNAL_USED_COUNT: Record<string, number> = {};

export type Status = 'unset' | 'loading' | 'ready' | 'error';

interface loadResult {
interface LoadResult {
ref: Element;
status: Status;
}

const loadScript = (path: string, props = {}): loadResult => {
type LoadExternal = <T>(path: string, props?: Partial<T>) => LoadResult;

const loadScript: LoadExternal = (path, props = {}) => {
const script = document.querySelector(`script[src="${path}"]`);

if (!script) {
Expand All @@ -58,7 +60,7 @@ const loadScript = (path: string, props = {}): loadResult => {
};
};

const loadCss = (path: string, props = {}): loadResult => {
const loadCss: LoadExternal = (path, props = {}) => {
const css = document.querySelector(`link[href="${path}"]`);
if (!css) {
coding-ice marked this conversation as resolved.
Show resolved Hide resolved
const newCss = document.createElement('link');
Expand Down
90 changes: 90 additions & 0 deletions packages/hooks/src/useProState/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { renderHook, act } from '@testing-library/react';
import useProState from '../index';

describe('useProState', () => {
const setUp = <T>(initialValue: T) =>
renderHook(() => {
const [state, { setState, getState, resetState, setMergeState }] =
useProState<T>(initialValue);
return {
state,
setState,
getState,
resetState,
setMergeState,
} as const;
});

it('should support initialValue', () => {
const hook = setUp(0);
expect(hook.result.current.state).toBe(0);
});

it('should support function initialValue', () => {
const hook = setUp(() => 0);
expect(hook.result.current.state).toBe(0);
});

it('should support update', () => {
const hook = setUp(0);
act(() => {
hook.result.current.setState(1);
});
expect(hook.result.current.state).toBe(1);
});

it('should support function update', () => {
const hook = setUp(0);
act(() => {
hook.result.current.setState((prev) => prev + 1);
});
expect(hook.result.current.state).toBe(1);
});

it('should support get latest value', () => {
const hook = setUp(0);
act(() => {
hook.result.current.setState(1);
});
expect(hook.result.current.getState()).toBe(1);
});

it('should support frozen', () => {
const hook = setUp(0);
const prevGetState = hook.result.current.getState;
act(() => {
hook.result.current.setState(1);
});
expect(hook.result.current.getState).toBe(prevGetState);
});

it('should keep random initialValue', () => {
const random = Math.random();
const hook = setUp(random);
act(() => {
hook.result.current.setState(Math.random());
hook.result.current.resetState();
});
expect(hook.result.current.state).toBe(random);
});

it('should keep random function initialValue', () => {
const random = Math.random();
const hook = setUp(() => random);
act(() => {
hook.result.current.setState(() => Math.random());
hook.result.current.resetState();
});
expect(hook.result.current.state).toBe(random);
});

it('should support setMergeState', () => {
const hook = setUp<{ hello?: string; foo?: string }>({
hello: 'world',
});
act(() => {
hook.result.current.setMergeState({ foo: 'bar' });
});
expect(hook.result.current.state).toEqual({ hello: 'world', foo: 'bar' });
});
});
26 changes: 26 additions & 0 deletions packages/hooks/src/useProState/demo/demo1.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* title: Open console to view logs
* desc: The counter prints the value every 3 seconds
*
* title.zh-CN: 打开控制台查看输出
* desc.zh-CN: 计数器每 3 秒打印一次值
*/

import React, { useEffect } from 'react';
import { useProState } from 'ahooks';

export default () => {
const [state, { setState, getState }] = useProState<number>(0);

useEffect(() => {
const interval = setInterval(() => {
console.log('interval count', getState());
}, 3000);

return () => {
clearInterval(interval);
};
}, []);

return <button onClick={() => setState((count) => count + 1)}>count: {state}</button>;
};
44 changes: 44 additions & 0 deletions packages/hooks/src/useProState/demo/demo2.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* title: Friendly reminder
* desc: SetMergeState will automatically merge objects. The usage of setState is consistent with useState in hook.
*
* title.zh-CN: 温馨提示
* desc.zh-CN: setMergeState会自动合并对象,setState和hook中useState的用法一致。
*/

import React from 'react';
import { useProState } from 'ahooks';

interface State {
hello: string;
value: number;
[key: string]: any;
}

export default () => {
const [state, { setState, resetState, setMergeState }] = useProState<State>({
hello: '',
value: Math.random(),
});

return (
<div>
<pre>{JSON.stringify(state, null, 2)}</pre>
<p>
<button type="button" onClick={() => setState({ hello: 'world', value: Math.random() })}>
set hello and value
</button>
<button
type="button"
onClick={() => setMergeState({ foo: 'bar' })}
style={{ margin: '0 8px' }}
>
setMergeState foo
</button>
<button type="button" onClick={resetState}>
resetState
</button>
</p>
</div>
);
};
65 changes: 65 additions & 0 deletions packages/hooks/src/useProState/index.en-US.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
---
nav:
path: /hooks
---

# useSetState

The hook that manage state, providing the ability to set, get the latest value, reset, and merge.

## Examples

### Get the latest value

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

### Merge and reset

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

## API

```typescript
export type SetMergeState<S extends Record<string, any>> = <K extends keyof S>(
state: Pick<S, K> | null | ((prevState: Readonly<S>) => Pick<S, K> | S | null),
) => void;
export type DispatchType<S> = Dispatch<SetStateAction<S>>;

function useProState<S extends Record<string, any>>(
initialState?: S | (() => S),
): [
S,
{
setState: DispatchType<S>;
getState: () => S;
resetState: () => void;
setMergeState: SetMergeState<S>;
},
];

function useProState<S>(initialState?: S | (() => S)): [
S,
{
setState: DispatchType<S>;
getState: () => S;
resetState: () => void;
setMergeState: (s: Record<string, any>) => void;
},
];
```

### Result

| Property | Description | Type | Default |
| ------------- | -------------------- | ------------------------------------------------------ | ------- |
| state | Current state | `S` | - |
| setState | Set state | `DispatchType<S>` | - |
| getState | Get the latest value | `() => S` | - |
| resetState | reset state | `() => void` | - |
| setMergeState | merge state | `SetMergeState<S> | (s: Record<string, any>) => void` | - |

### Params

| Property | Description | Type | Default |
| ------------ | ------------- | -------------- | ------- |
| initialState | Initial state | `T \| () => T` | - |
Loading
Loading