Reputation: 779
I am trying to update my state with the new following array, however Even though the console shows no errors and prints out the new array correctly as it should be formed, the state does not update to reflect this.
What am I doing wrong?
state = {
notes: [
{
text: "mow the lawn",
author: "dean",
time: "10am"
},
{
text: "feed the dog",
author: "sam",
time: "2pm"
}
]
};
updateNotes = (title, name, eventTime) => {
let newNote = {
text: title,
author: name,
time: eventTime
};
this.setState(state => {
const list = state.notes.concat(newNote);
console.log(list); //shows the list formed correctly in the console
return {
list
};
});
};
Also for reference here is what I see in the console after running the code assuming I input the values, new text, some author, and 3pm when creating my new note
(3) [{…}, {…}, {…}]
0: {text: "mow the lawn", author: "dean", time: "10am"}
1: {text: "feed the dog", author: "sam", time: "2pm"}
2: {text: "new text", author: "some author", time: "3pm"}
Upvotes: 0
Views: 250
Reputation: 41913
Why do you update a field that is called list
, even if your notes are inside field called notes
?
{ list }
is a shorthand to create an object with field called list and value that is stored in variable named in the same way.
Just update the proper field:
return {
notes: list,
};
Upvotes: 2
Reputation: 1827
It should be:
return {
notes: list
};
What you are doing now is adding a new variable list
to the state.
Upvotes: 3