Skip to content

Instantly share code, notes, and snippets.

@iamdanthedev
Last active March 16, 2018 06:47
Show Gist options
  • Select an option

  • Save iamdanthedev/12a45795ad45e5f9b08a96aa8b0caabf to your computer and use it in GitHub Desktop.

Select an option

Save iamdanthedev/12a45795ad45e5f9b08a96aa8b0caabf to your computer and use it in GitHub Desktop.

Revisions

  1. iamdanthedev revised this gist Mar 16, 2018. 1 changed file with 4 additions and 0 deletions.
    4 changes: 4 additions & 0 deletions SomeContainer.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    export default compose<Props, OwnProps>(
    withHistory,
    withRouteBlock("Already leaving?")
    )(SomeContainer);
  2. iamdanthedev created this gist Mar 16, 2018.
    51 changes: 51 additions & 0 deletions withRouteBlock.ts
    Original 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();
    }
    }
    })

    );