1

I am trying to update the state, but the state is not getting updated as expected. Partially gets updated. I need help in updating the updatedData data. My state is as below.

this.state = {
      userData: {
        accounts: { '82345': 'Data 1' },
        jobTitle: { '79438': 'Data 2' },
        state: { '82099': 'Data 3' },
        country: { '82008': 'Data 4' },
      },
      updatedData: {
        firstName: ‘Parul’,
        lastName: ‘Rathod’,
        mail: parulRathod@gmail.com,
        accounts: '',
        jobTitle: '',
        state: '',
        country: '',
      },
    };
  }

I need the data to be saved as

accounts: { label: 'Data 1', value: '82345' },
jobTitle: { label: 'Data 2', value: '79438' },
state: { label: 'Data 3', value: '82099' },
country: { label: 'Data 4', value: '82008' },

I have tried using the below method to do the required steps, but only country gets updated, and the rest remains as the previous state.

setUserData = () => {
    for (const key of Object.keys(this.state.userData)) {
      if(typeof (this.state.userData[key]) === 'object') {
        const seperator = this.state.userData[key];
        if(seperator) {
          const values = Object.values(seperator);
          const keys = Object.keys(seperator);
          const data = { label: values[0], value: keys[0] };
          if (key === 'country') {
            this.setState({
              updatedData: {
                ...this.state.updatedData,
                country: data,
              },
            });
          } else if (key === 'accounts') {
            this.setState({
              updatedData: {
                ...this.state.updatedData,
                accounts: data,
              },
            });
          } else if (key === 'state') {
            this.setState({
              updatedData: {
                ...this.state.updatedData,
                state: data,
              },
            });
          } else if (key === 'jobTitle') {
            this.setState({
              updatedData: {
                ...this.state.updatedData,
                jobTitle: data,
              },
            });
          }
        }
      }
    }
  }

0 Answers0