Last active
March 16, 2018 06:47
-
-
Save iamdanthedev/12a45795ad45e5f9b08a96aa8b0caabf to your computer and use it in GitHub Desktop.
withRouteBlock HOC to prevent transitions
This file contains hidden or 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
export default compose<Props, OwnProps>( | |
withHistory, | |
withRouteBlock("Already leaving?") | |
)(SomeContainer); |
This file contains hidden or 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 { compose, lifecycle, withState } from 'recompose'; | |
import { History, UnregisterCallback } from 'history'; | |
type Props = { | |
pristine: boolean; | |
history: History; | |
}; | |
type State = { | |
historyBlock: UnregisterCallback; | |
}; | |
/** | |
* HOC that blocks history transition if props.pristine is false | |
*/ | |
export const withRouteBlock = (message: string) => compose( | |
lifecycle<Props, State>({ | |
componentDidMount() { | |
const { history, pristine } = this.props; | |
if (!history) { | |
console.warn('history in undefined'); | |
} | |
if (!pristine) { | |
this.setState({ historyBlock: history.block(message) }) | |
} | |
}, | |
componentWillReceiveProps(nextProps) { | |
const { history, pristine } = nextProps; | |
const historyBlock = this.state ? this.state.historyBlock : null; | |
if (!pristine && !historyBlock) { | |
this.setState({ historyBlock: history.block(message) }) | |
} | |
else if (historyBlock && pristine) { | |
historyBlock(); | |
} | |
}, | |
componentWillUnmount() { | |
if (this.state && this.state.historyBlock) { | |
this.state.historyBlock(); | |
} | |
} | |
}) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment