Skip to content

Commit

Permalink
Ensure dispatch from useFormState works in StrictMode (facebook#2…
Browse files Browse the repository at this point in the history
…8557)

Co-authored-by: Andrew Clark <git@andrewclark.io>
  • Loading branch information
2 people authored and AndyPengc12 committed Apr 15, 2024
1 parent c50c3c0 commit 7ace243
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
48 changes: 48 additions & 0 deletions packages/react-dom/src/__tests__/ReactDOMForm-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1295,4 +1295,52 @@ describe('ReactDOMForm', () => {
assertLog(['B']);
expect(container.textContent).toBe('B');
});

// @gate enableFormActions
// @gate enableAsyncActions
test('useFormState works in StrictMode', async () => {
let actionCounter = 0;
async function action(state, type) {
actionCounter++;

Scheduler.log(`Async action started [${actionCounter}]`);
await getText(`Wait [${actionCounter}]`);

switch (type) {
case 'increment':
return state + 1;
case 'decrement':
return state - 1;
default:
return state;
}
}

let dispatch;
function App() {
const [state, _dispatch, isPending] = useFormState(action, 0);
dispatch = _dispatch;
const pending = isPending ? 'Pending ' : '';
return <Text text={pending + state} />;
}

const root = ReactDOMClient.createRoot(container);
await act(() =>
root.render(
<React.StrictMode>
<App />
</React.StrictMode>,
),
);
assertLog(['0']);
expect(container.textContent).toBe('0');

await act(() => dispatch('increment'));
assertLog(['Async action started [1]', 'Pending 0']);
expect(container.textContent).toBe('Pending 0');

await act(() => resolveText('Wait [1]'));
assertLog(['1']);
expect(container.textContent).toBe('1');
});
});
2 changes: 2 additions & 0 deletions packages/react-reconciler/src/ReactFiberHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -2259,6 +2259,8 @@ function rerenderFormState<S, P>(
);
}

updateWorkInProgressHook(); // State

// This is a mount. No updates to process.
const state: Awaited<S> = stateHook.memoizedState;

Expand Down

0 comments on commit 7ace243

Please sign in to comment.