Skip to content

Instantly share code, notes, and snippets.

@jwill9999
Last active March 6, 2017 23:05
Show Gist options
  • Save jwill9999/da2db353ee42e86863544d64f71dcc8f to your computer and use it in GitHub Desktop.
Save jwill9999/da2db353ee42e86863544d64f71dcc8f to your computer and use it in GitHub Desktop.
React Redux error Handler
//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)
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*/
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