I'm filling out a form, until then, okay, the problem is when I press the input to send and form a json object with the states that I set up in my constructor, the json object that appears in my console.log is empty, then , by pressing the input with the same values again on the form, the json object this time appears with duplicate values.

return after an input
.
{  
   "string":"",
   "uint":""
}

return after two inputs. (duplicate values)
{  
   "string":[  
      "sensor1",
      "sensor1"
   ],
   "uint":[  
      "1",
      "1"
   ]
}


import React, { Component } from 'react';

export default class DHT11 extends Component {

    constructor(props) {
        super(props);
        this.arrayStr = [];
        this.arrayUint = [];
        this.auxUint = '';
        this.auxStr = '';
        this.state = {
            string: '',
            uint: '',
            greatness: ''
        }
    }

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

        this.arrayStr.push(this.auxStr);
        this.arrayUint.push(this.auxUint);

        this.setState({ string: this.arrayStr });
        this.setState({ uint: this.arrayUint });

        var json = JSON.stringify(this.state);
        console.log(json);
    }

    handleChange = e => {
        const { name, value } = e.target;
        // console.log(name, value);
        switch (name) {
            case 'str':
                this.auxStr = (value);
                break;
            case 'uint':
                this.auxUint = (value);
                break;
        }
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit} noValidate>

                <div className='id_sensor'>
                    <label htmlFor="ID"> ID Sensor </label>
                    <input
                        placeholder=""
                        type="text"
                        name="uint"
                        noValidate
                        onChange={this.handleChange}
                    />
                </div>

                <div className='id_sensor'>
                    <label htmlFor="Name"> Name </label>
                    <input
                        placeholder=""
                        type="text"
                        name="str"
                        noValidate
                        onChange={this.handleChange}
                    />
                </div>

                <div className="createAccount">
                    <button type="submit">Send Values</button>
                </div>
            </form>
        )
    }
}

1 Answers

0
jsdeveloper On Best Solutions

It might be that setState is not guaranteed to be synchronous and has not finished when you call console.log. However, you can add a callback which gets called when setState has finished:

this.setState({ string: this.arrayStr, uint: this.arrayUint }, () => {
    var json = JSON.stringify(this.state);
    console.log(json);
});