m4tt1mus
m4tt1mus

Reputation: 1641

React - Passing value to setState callback

I'm trying to pass a value determined outside my prevState callback into the function. Here is what I have:

uncheckAllUnsentHandler = (e) => {
    const newCheckMarkValue = e.target.checked;
    this.setState((prevState, props, newCheckMarkValue) => {
      const newUnsentMail = prevState.unsentMail.map(policy => {
        mail.willSend = newCheckMarkValue;
        return mail;
      });
      return {
        unsentMail: newUnsentMail
      }
    });
  }

newCheckMarkValue is undefined inside the map function and I'm not sure why.

Long description: I have a table where clients select whether they want to send mail or not. By default all mail items are checked in the table. In the header they have the ability to uncheck/check all. I'm trying to adjust the state of the mail items in the table to be unchecked (willSend is the property for that on Mail) when the header checkbox is clicked to uncheck. All of this works if I hardcode the willSend to true or false in code (ex: mail.willSend = true;) in the code below, but I can't seem to get the value of the of the checkbox in the header in.

Upvotes: 0

Views: 40

Answers (1)

Drew Reese
Drew Reese

Reputation: 203587

setState

The updater function takes only two arguments, state and props. state is a reference to the component state at the time the change is being applied.

(state, props) => stateChange

You can simply access the version of newCheckMarkValue enclosed in the outer scope of uncheckAllUnsentHandler.

uncheckAllUnsentHandler = (e) => {
  const newCheckMarkValue = e.target.checked;
  this.setState((prevState, props) => {
    const newUnsentMail = prevState.unsentMail.map(policy => {
      mail.willSend = newCheckMarkValue;
      return mail;
    });
    return {
      unsentMail: newUnsentMail
    }
  });
}

Upvotes: 1

Related Questions