Skip to content

Commit

Permalink
fix: updating state by spreading in latest state values, not stale ones
Browse files Browse the repository at this point in the history
The situation here is that the `setAnimate` is being called in a setTimeout callback.
By the time the callback has been called, the state may have been changed.  But,
the way this was written previous to this commit is that it would spread in the old values
of state.  Instead of doing that, we should use the callback method for setState(), which
takes the very latest state as it's first argument, and we spread that here instead.
  • Loading branch information
Clint Goodman committed Oct 2, 2022
1 parent 594acae commit 415ff17
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions src/useAnimate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,30 +49,33 @@ export default function useAnimate(props: UseAnimateProps): {
}

if (complete) {
setAnimate({
setAnimate((animate) => ({
...animate,
style: complete,
});
}));
}
}, secToMs(delay + duration));
}

return () =>
onCompleteTimeRef.current && clearTimeout(onCompleteTimeRef.current);
}, [isPlaying, onComplete]);
}, [animate, complete, delay, duration, isPlaying, onComplete]);

return {
isPlaying,
style,
play: React.useCallback((isPlaying) => {
setAnimate({
...animate,
style: {
...(isPlaying ? end : start),
transition,
},
isPlaying,
});
}, []),
play: React.useCallback(
(isPlaying) => {
setAnimate((animate) => ({
...animate,
style: {
...(isPlaying ? end : start),
transition,
},
isPlaying,
}));
},
[end, start, transition],
),
};
}

0 comments on commit 415ff17

Please sign in to comment.