Skip to content

Commit

Permalink
Merge pull request #53 from timolins/clear-timeouts
Browse files Browse the repository at this point in the history
Keep track of dismissed toasts
  • Loading branch information
timolins authored Mar 21, 2021
2 parents 1ed8c8e + 176bc05 commit 351e62a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 7 deletions.
43 changes: 42 additions & 1 deletion src/core/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,31 @@ interface State {
pausedAt: number | undefined;
}

const toastTimeouts = new Map<Toast['id'], ReturnType<typeof setTimeout>>();

const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return;
}

const timeout = setTimeout(() => {
toastTimeouts.delete(toastId);
dispatch({
type: ActionType.REMOVE_TOAST,
toastId: toastId,
});
}, 1000);

toastTimeouts.set(toastId, timeout);
};

const clearFromRemoveQueue = (toastId: string) => {
const timeout = toastTimeouts.get(toastId);
if (timeout) {
clearTimeout(timeout);
}
};

export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case ActionType.ADD_TOAST:
Expand All @@ -57,6 +82,11 @@ export const reducer = (state: State, action: Action): State => {
};

case ActionType.UPDATE_TOAST:
// ! Side effects !
if (action.toast.id) {
clearFromRemoveQueue(action.toast.id);
}

return {
...state,
toasts: state.toasts.map((t) =>
Expand All @@ -71,10 +101,21 @@ export const reducer = (state: State, action: Action): State => {
: reducer(state, { type: ActionType.ADD_TOAST, toast });

case ActionType.DISMISS_TOAST:
const { toastId } = action;

// ! Side effects ! - This could be execrated into a dismissToast() action, but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId);
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id);
});
}

return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toastId || action.toastId === undefined
t.id === toastId || toastId === undefined
? {
...t,
visible: false,
Expand Down
6 changes: 0 additions & 6 deletions src/core/toast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,6 @@ toast.dismiss = (toastId?: string) => {
type: ActionType.DISMISS_TOAST,
toastId,
});
setTimeout(() => {
dispatch({
type: ActionType.REMOVE_TOAST,
toastId,
});
}, 1000);
};

toast.remove = (toastId?: string) =>
Expand Down

1 comment on commit 351e62a

@vercel
Copy link

@vercel vercel bot commented on 351e62a Mar 21, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.