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: new hook useGetSet #530

Closed
wants to merge 3 commits into from
Closed
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ our [migration guide](https://react-hookz.github.io/web/?path=/docs/migrating-fr
— Like `useSafeState` but its state setter is throttled.
- [**`useValidator`**](https://react-hookz.github.io/web/?path=/docs/state-usevalidator--example)
— Performs validation when any of provided dependencies has changed.
- [**`useGetSet`**](https://react-hookz.github.io/web/?path=/docs/state-usegetset--example)
- React state hook that returns state getter function instead of raw state itself, this prevents subtle bugs when state is used in nested functions.

- #### Navigator

Expand Down
2 changes: 1 addition & 1 deletion src/__docs__/migrating-from-react-use.story.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,7 @@ Not implemented yet

#### useGetSet

Not implemented yet
See [useGetSet](/docs/state-useGetSet--example)

#### useGetSetState

Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export { useMap } from './useMap/useMap';
export { useMediatedState } from './useMediatedState/useMediatedState';
export { usePrevious } from './usePrevious/usePrevious';
export { useSafeState } from './useSafeState/useSafeState';
export { useGetSet } from './useGetSet/useGetSet';
export { useSet } from './useSet/useSet';
export { useToggle } from './useToggle/useToggle';
export { useThrottledState } from './useThrottledState/useThrottledState';
Expand Down
12 changes: 12 additions & 0 deletions src/useGetSet/__docs__/example.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import * as React from 'react';
import { useGetSet } from '../..';

export const Example: React.FC = () => {
const [get, set] = useGetSet(0);
const onClick = () => {
setTimeout(() => {
set(get() + 1);
}, 1000);
};
return <button onClick={onClick}>Clicked: {get()}</button>;
};
38 changes: 38 additions & 0 deletions src/useGetSet/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example.stories';
import { ImportPath } from '../../storybookUtil/ImportPath';

<Meta title="State/useGetSet" component={Example} />

# useGetSet

React state hook that returns state getter function instead of raw state itself, this prevents subtle bugs when state is used in nested functions.

#### Example

<Canvas>
<Story story={Example} inline />
</Canvas>

## Reference

```ts
export function useGetSet<S>(
initialState: IInitialState<S>
): [get: () => S, set: (nextState: INextState<S>) => void];
```

#### Importing

<ImportPath />

#### Arguments

- _**initialState**_ _`IInitialState<S>`_ - initial state or initial state setter as for `useState`

#### Return

Returns array alike `useState` does, but instead return a state value it return a getter function.

- _**[0]**_ _`S`_ - getter of current state
- _**[1]**_ _`(nextState?: INewState<S>) => void`_ - state setter as for `useState`.
62 changes: 62 additions & 0 deletions src/useGetSet/__tests__/dom.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { renderHook, act } from '@testing-library/react-hooks/dom';
import { useGetSet } from '../..';

const setUp = (initialValue: any) => renderHook(() => useGetSet(initialValue));

beforeEach(() => {
jest.useFakeTimers();
});

describe('useGetSet', () => {
it('should be defined', () => {
expect(useGetSet).toBeDefined();
});

it('should render', () => {
const { result } = setUp('foo');
expect(result.error).toBeUndefined();
});

it('should init getter and setter', () => {
const { result } = setUp('foo');
const [get, set] = result.current;
expect(get).toBeInstanceOf(Function);
expect(set).toBeInstanceOf(Function);
});

it('should get current value', () => {
const { result } = setUp('foo');
const [get] = result.current;
expect(get()).toBe('foo');
});

it('should set new value', () => {
const { result } = setUp('foo');
const [get, set] = result.current;
act(() => set('bar'));
const currentValue = get();
expect(currentValue).toBe('bar');
});

it('should get and set expected values when used in nested functions', () => {
const { result } = setUp(0);
const [get, set] = result.current;
const onClick = jest.fn(() => {
setTimeout(() => {
set(get() + 1);
}, 1000);
});

// simulate 3 clicks
onClick();
onClick();
onClick();

act(() => {
jest.runAllTimers();
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is way overcomplicated, why not to simply set state inside act?

act(()=>{
 set();
 set();
 set();
})


expect(get()).toBe(3);
expect(onClick).toHaveBeenCalledTimes(3);
});
});
62 changes: 62 additions & 0 deletions src/useGetSet/__tests__/ssr.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { renderHook, act } from '@testing-library/react-hooks/server';
import { useGetSet } from '../..';

const setUp = (initialValue: any) => renderHook(() => useGetSet(initialValue));

beforeEach(() => {
jest.useFakeTimers();
});

describe('useGetSet', () => {
it('should be defined', () => {
expect(useGetSet).toBeDefined();
});

it('should render', () => {
const { result } = setUp('foo');
expect(result.error).toBeUndefined();
});

it('should init getter and setter', () => {
const { result } = setUp('foo');
const [get, set] = result.current;
expect(get).toBeInstanceOf(Function);
expect(set).toBeInstanceOf(Function);
});

it('should get current value', () => {
const { result } = setUp('foo');
const [get] = result.current;
expect(get()).toBe('foo');
});

it('should set new value', () => {
const { result } = setUp('foo');
const [get, set] = result.current;
act(() => set('bar'));
const currentValue = get();
expect(currentValue).toBe('bar');
});

it('should get and set expected values when used in nested functions', () => {
const { result } = setUp(0);
const [get, set] = result.current;
const onClick = jest.fn(() => {
setTimeout(() => {
set(get() + 1);
}, 1000);
});

// simulate 3 clicks
onClick();
onClick();
onClick();

act(() => {
jest.runAllTimers();
});

expect(get()).toBe(3);
expect(onClick).toHaveBeenCalledTimes(3);
});
});
13 changes: 13 additions & 0 deletions src/useGetSet/useGetSet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useCallback, Dispatch, SetStateAction } from 'react';
import { IInitialState } from '../util/resolveHookState';
import { useSafeState, useSyncedRef } from '../index';

export function useGetSet<S>(
initialState: IInitialState<S>
): [get: () => S, set: Dispatch<SetStateAction<S>>] {
const [state, setState] = useSafeState(initialState);
const stateRef = useSyncedRef(state);

// eslint-disable-next-line react-hooks/exhaustive-deps
return [useCallback(() => stateRef.current, []), setState];
}