wtf going on React?
Last active
July 29, 2023 05:02
-
-
Save ellemedit/3b227b9c56c9d4a3f8c4925befe4524f to your computer and use it in GitHub Desktop.
React@canary async action bug monkey patch
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
// @gate enableAsyncActions | |
it('transition should be commited for long async action', async () => { | |
let startTransition; | |
function App() { | |
const [isPending, _startTransition] = React.useTransition(); | |
startTransition = _startTransition; | |
Scheduler.log(`isPending:${JSON.stringify(isPending)}`); | |
return null; | |
} | |
const root = ReactDOMClient.createRoot(container); | |
await act(async () => { | |
root.render(<App />); | |
}); | |
assertLog(['isPending:false']); | |
let resolvePromise; | |
let promise = new Promise((resolve) => { | |
resolvePromise = resolve; | |
}); | |
await act(() => { | |
startTransition(() => promise); | |
}); | |
assertLog(['isPending:true']); | |
await act(async () => { | |
Scheduler.unstable_advanceTime(5000); | |
resolvePromise(); | |
}); | |
assertLog(['isPending:false']); // it fails | |
await act(() => { | |
root.unmount(); | |
}); | |
}) |
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
function useMonkeyPatchedTransition() { | |
const [isPending, _startTransition] = useTransition(); | |
const [_, forceUpdate] = useState(0); | |
const startTransition: typeof _startTransition = useCallback((transitionScope) => { | |
_startTransition(() => { | |
let maybeThenable = transitionScope(); | |
if (maybeThenable == null) { | |
return; | |
} | |
maybeThenable.then( | |
() => forceUpdate((x) => x + 1), | |
() => forceUpdate((x) => x + 1) | |
); | |
return maybeThenable as any; | |
}); | |
}, []); | |
return [isPending, startTransition] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment