Skip to content
This repository has been archived by the owner on Apr 3, 2024. It is now read-only.

Fix effect cleanup #35

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
11 changes: 10 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -191,12 +191,21 @@ export function useEffectReducer<
>,
event: TEvent | FlushEvent
): AggregatedEffectsState<TState, TEvent> => {
// Remove stopped entities if any, but otherwise keep them around
// if they haven't been stopped yet since this means our cleanup
// useEffect hasn't been executed yet
entitiesToStop = entitiesToStop.some(
entity => entity.status === EntityStatus.Stopped
)
? entitiesToStop.filter(entity => entity.status !== EntityStatus.Stopped)
: entitiesToStop;

const nextEffectEntities: Array<EffectEntity<TState, TEvent>> = [];
const nextEntitiesToStop: Array<EffectEntity<TState, TEvent>> = [];

if (event.type === flushEffectsSymbol) {
// Record that effects have already been executed
return [state, stateEffectTuples.slice(event.count), nextEntitiesToStop];
return [state, stateEffectTuples.slice(event.count), entitiesToStop];
}

const exec = (
Expand Down
4 changes: 4 additions & 0 deletions test/useEffectReducer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -507,10 +507,14 @@ describe('useEffectReducer', () => {
const helloButton = getByTestId('send-hello');
const goodbyeButton = getByTestId('send-goodbye');

// Click each button twice to make sure no effect cleanup
// is skipped due to batching
fireEvent.click(helloButton);
fireEvent.click(helloButton);

setTimeout(() => {
fireEvent.click(goodbyeButton);
fireEvent.click(goodbyeButton);
}, 30);

await waitFor(() => {
Expand Down