histroy.push() is not working in react router, if my base route is same

Viewed 425

I have seen so many questions but haven't got the answer. When i do history.push('/user') when i am on '/dashboard', it works great because my base route is different i.e user!=dashboard. But when i am on route '/user' and now i want to go to history.push('/user/87'). Here the weird thing happens as base route is same user===user, my url change but my component did not render again. I have use the <Link> thing which the react-router-dom provides but it doesn't work too.

here is my root thing,

import { BrowserRouter } from 'react-router-dom'; //"^5.0.1"

ReactDOM.render((
  <Provider store={store}>
    <BrowserRouter>
      <AppContainer />
    </BrowserRouter>
  </Provider>
), document.getElementById('root'));

Please provide the solution it would be great help.

2 Answers

I found one trick with my colleague, we can use getDerivedStateFromProps and componentDidUpdate life cycles

state = {
  currentUrl: this.props.match.url,
}

static getDerivedStateFromProps(props, state) {
    let updatedState = {};

    if (props.match.url !== state.currentUrl) {
      updatedState.currentUrl = props.match.url;
    }

    return updatedState;
  }

  componentDidUpdate(prevProps) {
    if (prevProps.match.url !== this.state.currentUrl) {
      // re-initiate your state so that it can run your render lifecycle
      this.setInitialState(); 
    }
  }

We can also use useEffect hook by providing [this.props.match.url] in second argument so that when ever your url updates you can set your state.

maybe do a this.forceUpdate() right after you push or use :params

Related