Created
October 13, 2015 23:42
-
-
Save tnightingale/b78d33208c18e512c797 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 CONFIRM_MODAL_RESPONSE = "CONFIRM_MODAL_RESPONSE"; | |
export const SHOW_CONFIRM_MODAL = "SHOW_CONFIRM_MODAL"; | |
export function confirmDeleteItem(id) { | |
let message = `Are you sure you want to delete item: ${id}`, | |
context = {id}; | |
return showConfirmModal(message, 'confirmDeleteItem', context); | |
} | |
export function confirmModalResponse(response, tag, context = null) { | |
return { type: CONFIRM_MODAL_RESPONSE, response, tag, context }; | |
} | |
export function showConfirmModal(message, tag, context) { | |
return { type: SHOW_CONFIRM_MODAL, message, tag, context }; | |
} | |
// | |
// Reducers | |
// | |
import {SHOW_CONFIRM_MODAL, CONFIRM_MODAL_RESPONSE} from './actions'; | |
function confirmationModals(state = {}, action = null) { | |
switch (action.type) { | |
case SHOW_CONFIRM_MODAL: | |
// Temporarialy store confirmation action context. | |
let {message, tag, context} = action; | |
return state.merge({message, tag, context}); | |
case CONFIRM_MODAL_RESPONSE: | |
// Clear confirmation action context. | |
return state.merge({ | |
message: null, | |
tag: null, | |
context: {} | |
}); | |
} | |
return state; | |
} | |
// Delete item when confirmation of modal matching our tag is detected. | |
function items(state = {}, action = null) { | |
switch (action.type) { | |
// ... | |
case CONFIRM_MODAL_RESPONSE: | |
if (tag === 'confirmDelete') { | |
if (action.response) { | |
let {id} = action.context; | |
return state.removeIn(['items', id]); | |
} | |
} | |
break; | |
// ... | |
} | |
return state; | |
} | |
// | |
// ConfirmationModal component | |
// | |
import {connect} from 'react-redux'; | |
export default connect((state) => state.confirmationModals, (props) => { | |
let {dispatch, message, tag, context} = props, | |
handleConfirm = (e) => dispatch(confirmModalResponse(true, tag, context)), | |
handleCancel = (e) => dispatch(confirmModalResponse(false, tag)); | |
return !tag ? null : ( | |
<div className="modal modal-confirm"> | |
<p>{message}</p> | |
<button onClick={handleConfirm}>Confirm</button> | |
<button onClick={handleCancel}>Cancel</button> | |
</div> | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment