-
Notifications
You must be signed in to change notification settings - Fork 27
feat: add useAsyncSetState #12
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,7 +22,7 @@ | |
| }, | ||
| "jest": { | ||
| "preset": "@4c", | ||
| "setupFiles": [ | ||
| "setupFilesAfterEnv": [ | ||
| "./test/setup.js" | ||
| ] | ||
| }, | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| import React, { useCallback, useEffect, useRef, useState } from 'react' | ||
|
|
||
| type Updater<TState> = (state: TState) => TState | ||
|
|
||
| export type AsyncSetState<TState> = ( | ||
| stateUpdate: React.SetStateAction<TState>, | ||
| ) => Promise<TState> | ||
|
|
||
| /** | ||
| * A hook that mirrors `useState` in function and API, expect that setState | ||
| * calls return a promise that resolves after the state has been set (in an effect). | ||
| * | ||
| * This is _similar_ to the second callback in classy setState calls, but fires later. | ||
| * | ||
| * ```ts | ||
| * const [counter, setState] = useStateAsync(1); | ||
| * | ||
| * const handleIncrement = async () => { | ||
| * await setState(2); | ||
| * doWorkRequiringCurrentState() | ||
| * } | ||
| * ``` | ||
| * | ||
| * @param initialState initialize with some state value same as `useState` | ||
| */ | ||
| function useStateAsync<TState>( | ||
| initialState: TState | (() => TState), | ||
| ): [TState, AsyncSetState<TState>] { | ||
| const [state, setState] = useState(initialState) | ||
| const resolvers = useRef<((state: TState) => void)[]>([]) | ||
|
|
||
| useEffect(() => { | ||
| resolvers.current.forEach(resolve => resolve(state)) | ||
| resolvers.current.length = 0 | ||
| }, [state]) | ||
|
|
||
| const setStateAsync = useCallback( | ||
| (update: Updater<TState> | TState) => { | ||
| return new Promise<TState>((resolve, reject) => { | ||
| setState(prevState => { | ||
| try { | ||
| let nextState: TState | ||
| // ugly instanceof for typescript | ||
| if (update instanceof Function) { | ||
| nextState = update(prevState) | ||
| } else { | ||
| nextState = update | ||
| } | ||
|
|
||
| // If state does not change, we must resolve the promise because | ||
| // react won't re-render and effect will not resolve. If there are already | ||
| // resolvers queued, then it should be safe to assume an update will happen | ||
| if (!resolvers.current.length && Object.is(nextState, prevState)) { | ||
| resolve(nextState) | ||
| } else { | ||
| resolvers.current.push(resolve) | ||
| } | ||
| return nextState | ||
| } catch (e) { | ||
| reject(e) | ||
| throw e | ||
| } | ||
| }) | ||
| }) | ||
| }, | ||
| [setState], | ||
| ) | ||
| return [state, setStateAsync] | ||
| } | ||
|
|
||
| export default useStateAsync | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| import { mount } from 'enzyme' | ||
| import React from 'react' | ||
| import { act } from 'react-dom/test-utils' | ||
| import useStateAsync, { AsyncSetState } from '../src/useStateAsync' | ||
|
|
||
| describe('useStateAsync', () => { | ||
| it('should increment counter', async () => { | ||
| let asyncState: [number, AsyncSetState<number>] | ||
|
|
||
| function Wrapper() { | ||
| asyncState = useStateAsync<number>(0) | ||
| return null | ||
| } | ||
|
|
||
| mount(<Wrapper />) | ||
|
|
||
| expect.assertions(4) | ||
|
|
||
| const incrementAsync = async () => { | ||
| await act(() => asyncState[1](prev => prev + 1)) | ||
| } | ||
|
|
||
| expect(asyncState![0]).toEqual(0) | ||
|
|
||
| await incrementAsync() | ||
| expect(asyncState![0]).toEqual(1) | ||
|
|
||
| await incrementAsync() | ||
| expect(asyncState![0]).toEqual(2) | ||
|
|
||
| await incrementAsync() | ||
| expect(asyncState![0]).toEqual(3) | ||
| }) | ||
|
|
||
| it('should reject on error', async () => { | ||
| let asyncState: [number, AsyncSetState<number>] | ||
|
|
||
| function Wrapper() { | ||
| asyncState = useStateAsync<number>(1) | ||
| return null | ||
| } | ||
| class CatchError extends React.Component { | ||
| static getDerivedStateFromError() {} | ||
| componentDidCatch() {} | ||
| render() { | ||
| return this.props.children | ||
| } | ||
| } | ||
|
|
||
| mount( | ||
| <CatchError> | ||
| <Wrapper /> | ||
| </CatchError>, | ||
| ) | ||
|
|
||
| // @ts-ignore | ||
| expect.errors(1) | ||
|
|
||
| await act(async () => { | ||
| const p = asyncState[1](() => { | ||
| throw new Error('yo') | ||
| }) | ||
| return expect(p).rejects.toThrow('yo') | ||
| }) | ||
| }) | ||
|
|
||
| it('should resolve even if no update happens', async () => { | ||
| let asyncState: [number, AsyncSetState<number>] | ||
|
|
||
| function Wrapper() { | ||
| asyncState = useStateAsync<number>(1) | ||
| return null | ||
| } | ||
|
|
||
| mount(<Wrapper />) | ||
|
|
||
| expect.assertions(3) | ||
|
|
||
| expect(asyncState![0]).toEqual(1) | ||
|
|
||
| await act(() => expect(asyncState[1](1)).resolves.toEqual(1)) | ||
|
|
||
| expect(asyncState![0]).toEqual(1) | ||
| }) | ||
|
|
||
| it('should resolve after update if already pending', async () => { | ||
| let asyncState: [number, AsyncSetState<number>] | ||
|
|
||
| function Wrapper() { | ||
| asyncState = useStateAsync<number>(0) | ||
| return null | ||
| } | ||
|
|
||
| mount(<Wrapper />) | ||
|
|
||
| expect.assertions(5) | ||
|
|
||
| expect(asyncState![0]).toEqual(0) | ||
|
|
||
| const setAndAssert = async (n: number) => | ||
| expect(asyncState[1](n)).resolves.toEqual(2) | ||
|
|
||
| await act(() => | ||
| Promise.all([setAndAssert(1), setAndAssert(1), setAndAssert(2)]), | ||
| ) | ||
|
|
||
| expect(asyncState![0]).toEqual(2) | ||
| }) | ||
| }) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ok; you could also add another "should run resolve manually flag", but i guess eagerly resolving the first few is fine
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ah right in the case of a bunch of sets. yeah that's a good approach