Array type variable changes to string on setState

Viewed 74

How can I get the state and array to work consistently?

The results are so confusing and inconsistent.

This is state:

 this.state = {
            tutorSubjects: [],

        };

This is setting state; the first console.log logs the subject in an array, the second logs and empty array:

            const name = target.name;
            if (name === "tutorSubjects") {
                let subjects = this.state.tutorSubjects.concat(value);
                console.log(subjects)
                this.setState({
                    tutorSubjects: subjects
                },  console.log(this.state.tutorSubjects))
            }

this handles submit and logs th subject as a string without the array:

    handleSubmit = e => {
        console.log(this.state.tutorSubjects)
}

My main goal is to send an array to the server, and now it's sending a string.

I have not idea why, but now that I have changed the state to subjects and updated state like below, It works perfectly.

            if (name === "tutorSubjects") {
                let subjects = this.state.subjects.concat(value);
                console.log(subjects)
                this.setState({
                    subjects
                }, console.log(this.state.subjects))
            }
1 Answers

The callback argument to setState should be a callback function but you're not supplying it that way, instead you're evaluating console.log(...) immediately and displaying that before setState gets called.

Fix it by ensuring it runs after:

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

Your original code is roughly equivalent to:

let v = console.log(this.state.subjects);
this.setState({ subjects }, v);

Where clearly that's out of order when expressed that way.

Related