2

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))
            }
2
  • Could you please post separate working solution so that everyone knows this question has been resolved. Commented Aug 17, 2020 at 2:18
  • My question is still why did it work so wired Commented Aug 17, 2020 at 2:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.