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

Add unit test for bug with setting object/array in state in useEffect hook. Fix #1306 #1307

Merged
merged 2 commits into from
Sep 25, 2023
Merged
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
27 changes: 27 additions & 0 deletions packages/core/core.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,33 @@ describe('createPrompt()', () => {
await expect(answer).resolves.toEqual('up');
});

it('useEffect: works with setting state at once with objects', async () => {
const Prompt = (config: { message: string }, done: (value: string) => void) => {
const [value, setValue] = useState([1, 2]);

useEffect(() => {
setValue([1, 3]);
}, []);

useKeypress((key: KeypressEvent) => {
if (isEnterKey(key)) {
done(String(value));
}
});

return String(value);
};

const prompt = createPrompt(Prompt);
const { answer, events } = await render(prompt, { message: 'Question' });
events.keypress('enter');

// awaiting it instead of using await expect(answer).resolves.toEqual('1,3')
// as this produces a better error message.
const resolvedAnswer = await answer;
mokkabonna marked this conversation as resolved.
Show resolved Hide resolved
expect(resolvedAnswer).toEqual('1,3');
});

it('useEffect: re-run only on change', async () => {
const effect = vi.fn();
const effectCleanup = vi.fn();
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/lib/hook-engine.mts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,9 @@ export const effectScheduler = {
store.hooksEffect.forEach((effect) => {
effect();
});
// Warning: Clean the hooks before exiting the `withUpdates` block.
// Failure to do so means an updates would hit the same effects again.
store.hooksEffect.length = 0;
})();
store.hooksEffect.length = 0;
},
};
Loading