user12990369
user12990369

Reputation:

How do i make state reset inside nested routes

I've noticed every time the profile:id is changed to one and another(/profile/1 -> profile/2), the state inside the profile component isn't changed.

Is there a way to "reset" the component state when the :id is changed? I am having trouble trying to figure this out.

My code looks something like this

<Route path ='/profile/:id/' component={ Profile } />

componentDidMount(){
        document.addEventListener('scroll', this.trackScrolling);
 }
componentWillUnmount(){
        document.removeEventListener('scroll', this.trackScrolling);
    }
trackScrolling = () => {
        const wrappedElement = document.getElementById('lastElement');
        if (this.isBottom(wrappedElement)) {
            this.setState({render_count: this.state.render_count+1});
        }
};
isBottom(el) {
        return el.getBoundingClientRect().bottom <= window.innerHeight;
}

Upvotes: 0

Views: 76

Answers (1)

gdh
gdh

Reputation: 13682

Try the following:

  • Grab the id from the url using match.params from props
  • Use componentDidUpdate to change the state of the component
componentDidUpdate(prevProps){
   if(prevProps.match.params.id !== this.props.match.params.id) {
     this.setState({
      render_count: 0
     })
   }
}

Upvotes: 1

Related Questions