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.

2

3 Answers 3

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});
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is the safest way.
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 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];
    }, [])
  }
}));

Comments

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

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.