Skip to content

Instantly share code, notes, and snippets.

@raddeus
Created July 12, 2019 16:00
Show Gist options
  • Save raddeus/4a37ddae68a89ea0a893dd08f6456ee8 to your computer and use it in GitHub Desktop.
Save raddeus/4a37ddae68a89ea0a893dd08f6456ee8 to your computer and use it in GitHub Desktop.
// Actions
export const ADD_TOAST = "ADD_TOAST";
export const DISMISS_TOAST = "DISMISS_TOAST";
// Action Creator
export function addToast(toast) {
toast = { ...toast, id: Math.random() };
return function(dispatch) {
dispatch({
type: ADD_TOAST,
toast
});
setTimeout(() => {
dispatch({
type: DISMISS_TOAST,
toast
});
}, toast.timeout || 1500);
};
}
// Reducer
const toastInitialState = {
toasts: []
};
function toastReducer(state = toastInitialState, action) {
switch (action.type) {
case ADD_TOAST:
return {
...state,
toasts: [...state.toasts, action.toast]
};
case DISMISS_TOAST:
return {
...state,
toasts: state.toasts.filter(
toast => toast.id !== action.toast.id
)
};
default:
return state;
}
}
// Dispatching a toast looks like this:
dispatch(addToast({ message: "Logged In!" }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment