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))
}