Skip to content

Instantly share code, notes, and snippets.

@Ranatchai
Created August 8, 2019 03:48
Show Gist options
  • Save Ranatchai/0505f80a9808795508e87ea28eaeaef9 to your computer and use it in GitHub Desktop.
Save Ranatchai/0505f80a9808795508e87ea28eaeaef9 to your computer and use it in GitHub Desktop.
import React from 'react'
import { withRouter } from 'utils/native'
import { some } from 'lodash'
export const HistoryStackContext = React.createContext()
export const HistoryStackConsumer = HistoryStackContext.Consumer
export const HistoryStack = withRouter(
class HistoryStack extends React.Component {
constructor(props) {
super()
this.state = {
currentRoute: this.getHistoryState(props),
prevRoute: null,
prevRoutes: []
}
}
componentDidUpdate(prevProps) {
if (prevProps.location !== this.props.location) {
const currentRoute = this.state.currentRoute
this.setState({
currentRoute: this.getHistoryState(this.props),
prevRoute: currentRoute,
prevRoutes: this._isBack
? this.state.prevRoutes
: [...this.state.prevRoutes, currentRoute]
})
delete this._isBack
}
}
getHistoryState(props) {
return {
pathname: props.location.pathname,
search: props.location.search,
url: props.location.pathname + props.location.search
}
}
goBack = () => {
this._isBack = true
const prevRoute = this.state.prevRoute
const prevRoutes = this.state.prevRoutes.slice(
0,
this.state.prevRoutes.length - 1
)
this.setState({
currentRoute: prevRoute,
prevRoute: prevRoutes[prevRoutes.length - 1],
prevRoutes
})
this.props.history.goBack()
}
pushState = (...args) => {
return this.props.history.push(...args)
}
render() {
return (
<HistoryStackContext.Provider
value={{
currentRoute: this.state.currentRoute,
prevRoute: this.state.prevRoute,
prevRoutes: this.state.prevRoutes,
pushState: this.pushState,
goBack: this.goBack
}}
>
{this.props.children}
</HistoryStackContext.Provider>
)
}
}
)
export const BackHandler = ({ children, pathExceptions }) => {
return (
<HistoryStackConsumer>
{({ prevRoute, goBack, pushState }) =>
children({
goBack: () => {
if (
prevRoute &&
!/redirect/.test(prevRoute.pathname) &&
!some(pathExceptions, pathException => {
return (prevRoute.pathname || '').includes(pathException)
})
) {
goBack()
} else {
pushState('/order-list-v2')
}
}
})
}
</HistoryStackConsumer>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment