Last active
March 6, 2017 23:05
-
-
Save jwill9999/da2db353ee42e86863544d64f71dcc8f to your computer and use it in GitHub Desktop.
React Redux error Handler
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 addError = (message) => | |
({ | |
type: ADD_ERROR, | |
payload: message | |
}) | |
export const clearError = index => | |
({ | |
type: CLEAR_ERROR, | |
payload: index | |
}) | |
//error handler | |
const handleError = error => { | |
store.dispatch( | |
addError(error.message) | |
) | |
} | |
//eventlistener | |
window.addEventListener("error", handleError) |
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
import Menu from './ui/Menu' | |
import ShowErrors from './containers/ShowErrors' | |
export const App = ({children}) => | |
<div className="app"> | |
<ShowErrors /> | |
{children} | |
<Menu /> | |
</div> | |
export const Whoops404 = ({ location }) => | |
<div className="whoops-404"> | |
<h1>Whoops, route not found</h1> | |
<p>Cannot find content for {location.pathname}</p> | |
</div> | |
/*import in routes*/ |
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
import {PropTypes} from 'react' | |
import { clearError } from '../../actions' | |
import { connect } from 'react-redux' | |
export const ShowErrors = ({errors = [], onClearError = f => f}) => | |
<div className = "show-errors" > {(errors.length) | |
? errors.map((message, i) => | |
<div key={i} className="error"> | |
<p>{message}</p> | |
<CloseButton onClick={() => onClearError(i)}/> | |
</div>) | |
: null} | |
</div> | |
ShowErrors.propTypes = { | |
errors: PropTypes.array, | |
onClearError: PropTypes.func | |
} | |
const mapStateToProps = state => { | |
return { | |
errors: state.errors | |
} | |
} | |
const mapDispatchToProps = dispatch => { | |
return { | |
onClearError(index) { | |
dispatch( | |
clearError(index) | |
) | |
} | |
} | |
} | |
module exports = connect(mapStateToProps,mapDispatchToProps)(ShowErrors) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment