Last active
March 16, 2018 06:47
-
-
Save iamdanthedev/12a45795ad45e5f9b08a96aa8b0caabf to your computer and use it in GitHub Desktop.
Revisions
-
iamdanthedev revised this gist
Mar 16, 2018 . 1 changed file with 4 additions and 0 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,4 @@ export default compose<Props, OwnProps>( withHistory, withRouteBlock("Already leaving?") )(SomeContainer); -
iamdanthedev created this gist
Mar 16, 2018 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,51 @@ 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(); } } }) );