1

There is a classic handle Change function. I can change the data in the same directory. There is no problem. but I have sub-data. I can't change them. I want to handle this as clean without typing the extra functions in handlechange. How can I do it?

My state:

 this.state = {
            formData: {
                appointedBroker: '',
                propertyInformations: {
                    rent: false,
                    property: {
                        housing: false,
                    },
                    features: {
                        rooms: ""
                    },
                    location: ""
                },
            }
        }

my handleChange Function:

 handleChange(event) {
        const { formData } = this.state;
        formData[event.target.name] = event.target.value;
        this.setState({ formData });
    }

and my inputs

        <TextField
            value={propertyInformations.features.rooms}
            onChange={(e) => this.handleChange(e)}
            id="rooms"
            name={'rooms'}
            type={'text'}
            label={t('Rooms')} />

in this case, I just changed "appointedBroker" data For example; I want to change "rooms"

1
  • Flatten your data, remove the nesting. Commented Sep 3, 2020 at 9:35

2 Answers 2

2

In your handleChange function, you are directly mutating the state which goes against the React pattern. Doing this way, will make the update undetected e.g by componentDidUpdate.

The recommended way would be something along this lines:

handleChange(event) {
       this.setState(prevState => ({
          formData: {
            ...prevState.formData ,
            [prevState.formData.propertyInformations.features.rooms]: e.target.value,
          },
         }));
    }
Sign up to request clarification or add additional context in comments.

Comments

1

the code in handleChange should be like this

const updatedFormData = {...this.state.formData,
   propertyInformations : {
       ...this.state.formData.propertyInformations,
       property: {
           ...this.state.formData.propertyInformations.property,
           rooms: e.target.value
}}}

this.setState({ formData: updatedFormData })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.