2

I have a simple react form but when I console log my object in state it comes up as empty values. I have been sitting for a while now trying to get my values in. When i console log the event I get the values in my console, but I cant console log my state object. Here is my code:

handleSubmit = (event: any) => {
event.preventDefault();
event.persist();
this.setState({
  IPObject: {
    Name: event.target[0].value,
    IPList: event.target[1].value,
    priority: event.target[2].value,
    rule: event.target[3].value
  }
})
console.log(this.state.IPObject)


render() {
return (
  <Form className="mui-form" onSubmit={this.handleSubmit}>
    <legend>Add your IP address</legend>
    <label>Your Name</label>

    <Input placeholder="Name" required={true}></Input>
    <label>Your IP Address</label>
    <Input placeholder="IP address" required={true}></Input>
    <label>Priority Rule (Add any number from 400 and above)</label>
    <Input placeholder="Priority Rule" required={true}></Input>
    <label>Subnet (Leave on 24 by default) Unless you know what you doing</label>
    <Select defaultValue="24">
      <Option value="32" label="32"></Option>
      <Option value="24" label="24"></Option>
    </Select>
    <br></br>
    <Button variant="raised">Add IP</Button>
  </Form>
);

and this is in my state:

this.state = {
  IPObject: {
    priority: "",
    IPList: "",
    rule: "",
    Name: ""
  }
}
  • Does this answer your question? [setState doesn't update the state immediately](https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately) – ggorlen Mar 28 '21 at 08:33
  • `setState` is asynchronous. You won't see the value until the next render. – ggorlen Mar 28 '21 at 08:34

3 Answers3

1

setState is async function, use like this for getting result:

this.setState({...}, ()=>{console.log(...)});

and in your code:

this.setState({
  IPObject: {
    Name: event.target[0].value,
    IPList: event.target[1].value,
    priority: event.target[2].value,
    rule: event.target[3].value
  }
}, ()=>{
  console.log(this.state.IPObject)
})
Babak Yaghoobi
  • 1,892
  • 9
  • 18
1

Your assumption is wrong, you can't procedurally & synchronously update the state and then log it the next line, because technically the console.log will trigger before your actual state update. If you want to track state changes, use useEffect/componentDidUpdate and track the state change.

Ognjen Mišić
  • 1,219
  • 17
  • 37
0

Try this

handleSubmit = (event: any) => {
  event.preventDefault();
  event.persist();
  this.setState({
      IPObject: {
      Name: event.target[0].value,
      IPList: event.target[1].value,
      priority: event.target[2].value,
      rule: event.target[3].value
  }
}, () => {

 console.log(this.state.IPObject)

})
user1155773
  • 74
  • 1
  • 8