Farouk YD
Farouk YD

Reputation: 102

redirect to the same component re render

I'm using the same Form component for editing a post and adding a new one in my application. The componentDidMount of Form looks like this:

componentDidMount() {
    this.props.match ? this.props.dispa({
        type: 'ON_LOAD_ACTION',
        payload: this.props.fetch.data.find(x => x.id == this.props.match.params.id)
    }) : this.props.dispa({
        type: 'ON_RESET',
        payload: ''
    });
}

It checks if there's an id on the URL, e.g. localhost:3000/edit/id

I'm trying to update a post. I extract the data of the post and I can fill the form with it. If there's no id on the URL I just render the form empty. The second dispatch is for resetting the state to its initial state.

I'm using react-router/redux and my problem is when I'm on the edit form and click on create form. It doesn't re-render and I got the value of the post I was in. I think that it's because i'm redirecting to the same form.

     <Route exact path="/create" >
       <FromProduct />
       </Route>
     <Route exact path="/edit/:id" component={FromProduct}></Route>

But if I click on submit button to update the post or I go to the /home first, the component re-renders perfectly.

Upvotes: 1

Views: 788

Answers (1)

Inacio Schweller
Inacio Schweller

Reputation: 1986

There are different ways to see the problem:

  1. React-router doesn't unmounts FromProduct component on each Route change. This is causing the behavior you described, you're seeing the same component always. You could try to force a re-render with an inline function.
  2. Since your componentDidMount is not being called again, you can use componentWillReceiveProps on the FromProduct component. This way, for each Route change, it'll be executed even if it was mounted, because it'll now receive new props.

Solution #1 is not really recommended. The solution #2 would be doing something like this:

componentWillReceiveProps(newProps) {
  // very similar logic for componentDidMount
  // but use newProps instead of this.props
}

If you still want to try Solution #1, please check React router's documentation about inline rendering here.

Upvotes: 1

Related Questions