@
@
@Richswitch2018-07-26 22:17:14
JavaScript
@Richswitch, 2018-07-26 22:17:14

Why can't I do setState in handleSubmit()?

Hey!
Can't change state after form submission. I think this is due to the asynchrony of setState , but I could be wrong.
In my case it looks something like this

...
  handleSubmit(e) {
    e.preventDefault();

    this.request(e.target);

    this.setState({
      ...this.state,
      currentState: {
        ...this.state.currentState,
        submited: true
      }
    });
  }

  render() {
    return (
      <Items>
        { this.state.mailData.map((data, i) => {
          return (
            <ItemRow key={'row-' + i} onSubmit={this.handleSubmit}>
              <ItemInput>
                <input id={data.id} type="checkbox" />
                <label htmlFor={data.id}></label>
              </ItemInput>
              <Item>
                <input type="email" name="email" value={data.email} disabled/>
              </Item>
              <Item> 
                <input type="text" name="name" value={data.name} disabled/>
              </Item>
              <Item>
                <p data-status={data.status}>{JSON.parse(data.status) ? 'Sent' : 'Unsent'}</p>
              </Item>
              {!data.status && 
                <ButtonSend type="submit" onClick={this.handleClick}>Send</ButtonSend>
              }

            </ItemRow>
          );
        })
        }
      </Items>
    );
  }

when submitting, this.request(e.target) works as it should, but setState does not work at all.
PS how can i change the state after request. In the .then function, I cannot get the this context

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-07-26
_

when submitting, this.request(e.target) works as it should, but setState does not work at all.

Should work. Are you sure handleSubmit is bound to the component's context?
If not, then it can be done like this:
handleSubmit = e => {

};

The call to setState can be shortened to:
this.setState({
      currentState: {
        ...this.state.currentState,
        submited: true,
      },
    });

You can:
this.request(e.target).then(() => {
    this.setState({
      currentState: {
        ...this.state.currentState,
        submited: true
      }
    });
});

Or you can use an async function:
handleSubmit = async e => {
    e.preventDefault();
    await this.request(e.target);

    this.setState({
      currentState: {
        ...this.state.currentState,
        submited: true
      }
    });
  };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question