Enzo
Enzo

Reputation: 318

Render Component every time it's get clicked

I have a List of country that shows name and id. I want to able to edit the countries, so i add it edit button for each row. the structure of component is like :

ListComponent
 -- Edit Component // will show a modal
 --- Modal Component
 ---- Form Component

I should fill the form whenever modal is open, now the question is : which life cycle method should i use to fill the form ?

componentDidMount only fire once.

componentDidUpdate won't trigger on first call and will trigger afterward.

Code :

  componentDidMount(prevProps, prevState) {
      if(this.props.status == 'update') {
        this.props.form.setFieldsValue({
          isForeign: this.props.country.isForeign,
          name: this.props.country.name,
        });
      }
  }

Upvotes: 1

Views: 41

Answers (2)

Craig Gehring
Craig Gehring

Reputation: 3377

If you want to handle start AND updates in a class component, you have to use both lifecycle methods. That’s a big reason why React implemented hooks for functional components, to avoid the redundancy.

https://reactjs.org/docs/hooks-intro.html

Upvotes: 1

Tony
Tony

Reputation: 20162

You can use componentWillReceiveProps

componentWillReceiveProps: Executed when particular prop updates to trigger state transitions.

Small example from my code base

   componentWillReceiveProps(nextProps) {
            if (this.props.userId !== nextProps.userId) {
                    const url = `${ROLE_API}/${nextProps.userId}`;
                    Get(url).then(res => {
                            this.setState({rolesName: res.data.rolesName, 
                             currentUserRoles: res.data.currentUserRoles,
                             userId: res.data.userId});
                    });
            }
    }

Upvotes: 0

Related Questions