Created
January 7, 2018 18:31
-
-
Save iamdanthedev/271db281324f95762b671451f6420177 to your computer and use it in GitHub Desktop.
react hoc that blocks history transition
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 { 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 withFormBlock = (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