blankface
blankface

Reputation: 6347

Set state for array of object

I have a react component that has a state attribute called Report. It conforms to the following interface:

interface Report {
  firstname: string;
  lastname: string;
  otherinfo: info[];
}

interface info {
  dob: string;
  gender: string;
  email: string;
}

I'd like to know the preferred way of doing setState if I want to update the value of email.

Upvotes: 0

Views: 1030

Answers (3)

Dimo
Dimo

Reputation: 487

I wonder if you could use Immutability-helper for your use case? Something along the lines of:

const newReport = update(report, { otherinfo: { email: { $set: newEmail }}}); this.setState({report: newReport})

Upvotes: 0

Rohith Murali
Rohith Murali

Reputation: 5669

You can use the following method where report is the state variable holding your Report object.

UpdateEmail(emailValue, index){
  let report = {...this.state.report};
  let info = [...report.otherinfo];
  let newInfoObj = info[index] //index of the state object u want to update
  newInfoObj.email = emailValue;
  info[index] = newInfoObj;
  report.otherinfo = info;
  this.setState({report : report});
}

Upvotes: 1

albert
albert

Reputation: 474

I believe something like this should work.

const targetIndex = 0; // assuming this is the index of the element you want to update
const newEmail = '[email protected]'; // new email address to be set

this.setState(prevState => ({
  ...prevState,
  report: {
    ...prevState.report,
    otherinfo: prevState.report.otherinfo.reduce((accum: info[], currrent: info, currentIndex: number) => {
      if (currentIndex === targetIndex) { // this is where we're trying to find the element with the matching index
        return [
          ...accum,
          {
            ...current,
            email: newEmail, // this is where we set the new email
          }
        ]
      }
      return [...accum, current];
    }, [])
  }
}));

Upvotes: 0

Related Questions