0

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.

blankface
  • 5,757
  • 19
  • 67
  • 114
  • Use filtering, array spread, and object spread. – Andrew Li May 09 '18 at 05:24
  • Possible duplicate of [React: How do I update state.item\[1\] on setState? (with JSFiddle)](https://stackoverflow.com/questions/29537299/react-how-do-i-update-state-item1-on-setstate-with-jsfiddle) – MichaelS May 09 '18 at 05:30

3 Answers3

1

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});
}
Rohith Murali
  • 5,551
  • 2
  • 25
  • 26
0

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@example.com'; // 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];
    }, [])
  }
}));
albert
  • 464
  • 2
  • 7
0

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})

Dimo
  • 467
  • 6
  • 13