-1

I have change function but setState not work how to fix this issue all value setState blank how to this issue solve

 handleAddressSubmit = (e) => {
e.preventDefault();
let isValidForm = false;
this.props.form.validateFieldsAndScroll((err, values) => {
  if (!err) {
    isValidForm = true;
  }
});
if (!isValidForm) {
  return false;
}

if (this.state.flatno) {
  this.setState({
    full_address:
      this.state.flatno +
      "," +
      this.state.address1 +
      "," +
      this.state.suburb +
      "," +
      this.state.state +
      "," +
      this.state.post_code +
      "," +
      this.state.country,
  });
} else {
  this.setState({
    full_address:
      this.state.address1 +
      "," +
      this.state.suburb +
      "," +
      this.state.state +
      "," +
      this.state.post_code +
      "," +
      this.state.country,
  });
}

console.log(this.state.is_default);
this.props.addAddressAction({
  flat_no: this.state.flatno,
  address1: this.state.address1,
  address2: this.state.address2,
  suburb: this.state.suburb,
  state: this.state.state,
  postal_code: this.state.post_code,
  country: this.state.country,
  full_address: this.state.full_address,
  lat: this.state.lataddress,
  lang: this.state.lngaddress,
  is_default: this.state.is_default,
});

this.setState({ flat_no: "", address1: "", address2: "", suburb: "", state: "", postal_code: "", country: "", full_address: "", lat: "", lang: "", is_default: "", });

};

  • setState is async, you must put console log as the callback ```this.setState({...}, () => console.log(this.state.init_values)``` – Alexey Nikonov May 20 '20 at 13:42

1 Answers1

0

You can't read the state value right after calling a state setter (this.setState or setState from useState). You will always have the old values.

You should read it in the next render.

The state setter just tells react to enqueue an update for a component. It doesn't mutate the state right away.

For a complete understanding of what setState does, I recommend this blog post from Dan

Incepter
  • 2,711
  • 15
  • 33
  • They could also use the optional callback function as the second parameter, which is guaranteed to execute after the state has been updated. – Brian Thompson May 20 '20 at 13:41
  • yeah I know, but the better way is to treat it like a sideEffect which is the case. I believe the true use case isn't console.log – Incepter May 20 '20 at 13:42
  • after submit form input not empty how to after blank form please help me – vineet pkt May 21 '20 at 12:15
  • In the submit function, you should set state to its initial values, and that all: `this.setState({ flat_no: "", address1: "", address2: "", suburb: "", state: "", postal_code: "", country: "", full_address: "", lat: "", lang: "", is_default: "", });` – Incepter May 21 '20 at 13:33
  • I have pass empty value but its not work – vineet pkt May 25 '20 at 04:07