Skip to content

Instantly share code, notes, and snippets.

@Temzasse
Last active May 28, 2017 20:20
Show Gist options
  • Save Temzasse/91fb8c66f38deb39509e352e5e94df33 to your computer and use it in GitHub Desktop.
Save Temzasse/91fb8c66f38deb39509e352e5e94df33 to your computer and use it in GitHub Desktop.
All necessary Redux reducers, actions, selectors etc for React.js Toaster component
import update from 'immutability-helper';
import { createAction } from 'redux-actions';
// Action types
export const TOAST_ADD_MESSAGE = 'TOAST_ADD_MESSAGE';
export const TOAST_REMOVE_MESSAGE = 'TOAST_REMOVE_MESSAGE';
export const initialState = {
messages: [],
};
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case TOAST_ADD_MESSAGE:
return update(state, {
messages: {
$push: [{
message: action.payload.message,
timeout: action.payload.timeout,
type: action.payload.type || 'INFO',
// TODO: could use proper id creation util here
id: new Date().getUTCMilliseconds(),
}],
},
});
case TOAST_REMOVE_MESSAGE: {
const newMessages = state.messages
.filter(msg => msg.id !== action.payload);
return update(state, { messages: { $set: newMessages } });
}
default:
return state;
}
}
// Actions
export const addToast = createAction(TOAST_ADD_MESSAGE);
export const removeToast = createAction(TOAST_REMOVE_MESSAGE);
// Custom Actions (shorthands)
export const addSuccess = (message) => ({
type: TOAST_ADD_MESSAGE,
payload: { type: 'SUCCESS', message }
});
export const addError = (message) => ({
type: TOAST_ADD_MESSAGE,
payload: { type: 'ERROR', message }
});
export const addWarning = (message) => ({
type: TOAST_ADD_MESSAGE,
payload: { type: 'WARNING', message }
});
// Selectors
export const getToasts = state => state.toast.messages;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment