Created
July 12, 2019 16:00
-
-
Save raddeus/4a37ddae68a89ea0a893dd08f6456ee8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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