Skip to content

Commit

Permalink
Lookup correct toaster for toast ID
Browse files Browse the repository at this point in the history
  • Loading branch information
timolins committed Jan 6, 2025
1 parent cb1fe8e commit e1603b0
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
12 changes: 7 additions & 5 deletions src/core/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,13 @@ export const dispatch = (action: Action, toasterId = DEFAULT_TOASTER_ID) => {
});
};

export const dispatchAll = (action: Action) => {
Object.keys(memoryState).forEach((toasterId) => {
dispatch(action, toasterId);
});
};
export const dispatchAll = (action: Action) =>
Object.keys(memoryState).forEach((toasterId) => dispatch(action, toasterId));

export const getToasterIdFromToastId = (toastId: string) =>
Object.keys(memoryState).find((toasterId) =>
memoryState[toasterId].toasts.some((t) => t.id === toastId)
);

export const createDispatch =
(toasterId = DEFAULT_TOASTER_ID) =>
Expand Down
16 changes: 14 additions & 2 deletions src/core/toast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ import {
resolveValue,
} from './types';
import { genId } from './utils';
import { createDispatch, Action, ActionType, dispatchAll } from './store';
import {
createDispatch,
Action,
ActionType,
dispatchAll,
getToasterIdFromToastId,
} from './store';

type Message = ValueOrFunction<Renderable, Toast>;

Expand Down Expand Up @@ -37,7 +43,11 @@ const createHandler =
(type?: ToastType): ToastHandler =>
(message, options) => {
const toast = createToast(message, type, options);
const dispatch = createDispatch(toast.toasterId);

const dispatch = createDispatch(
toast.toasterId || getToasterIdFromToastId(toast.id)
);

dispatch({ type: ActionType.UPSERT_TOAST, toast });
return toast.id;
};
Expand Down Expand Up @@ -84,7 +94,9 @@ toast.remove = (toastId?: string, toasterId?: string) => {
};
if (toasterId) {
createDispatch(toasterId)(action);
console.log('dispatch', action, toasterId);
} else {
console.log('dispatchAll', action);
dispatchAll(action);
}
};
Expand Down
1 change: 1 addition & 0 deletions test/toast.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,7 @@ describe('Multi-Toaster behavior', () => {

// Now update that toast to success
act(() => {
// Note that we are not providing a toasterId here
toast.success('Data saved!', {
id: toastId,
});
Expand Down

0 comments on commit e1603b0

Please sign in to comment.