Skip to content

Instantly share code, notes, and snippets.

@namelos
Last active December 6, 2015 07:37
Show Gist options
  • Save namelos/e6af02168be45e784e0e to your computer and use it in GitHub Desktop.
Save namelos/e6af02168be45e784e0e to your computer and use it in GitHub Desktop.
error handling higher order component & reducer
const mapState = ({ error }) => ({ error })
const mapDispatch = dispatch => bindActionCreators({ showErr, cancelErr }, dispatch)
@connect(mapState, mapDispatch)
export const error = ComposedComponent =>
class extends Component {
render = () => <div>
<ComposedComponent { ...this.props }
showErr={ this.props.showErr }
cancelErr={ this.props.cancelErr } />
<div onClick={ this.props.cancelErr } className="err"
style={{ display: this.props.error === null ? 'none' : 'block' }} >
<div className="err-msg">
{ this.props.error }
</div>
</div>
</div>
}
const START = 'app/error/START'
const CANCEL = 'app/error/CANCEL'
export const error = (state = null, action) => {
switch (action.type) {
case START:
return action.msg
case CANCEL:
return null
default:
return state
}
}
export const cancelErr = () => ({ type: CANCEL })
export const showErr = msg => dispatch => {
dispatch({ type: START, msg })
setTimeout( () => dispatch({ type: CANCEL }), 2000 )
}
@error
export default class MyComponent extends Component {
render = () => <h1 onClick={ this.props.showErr('OOOPS!') }>
Click Me To Show Error!
<h1>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment