0

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

2 Answers 2

3

It should be:

return {
  notes: list
};

What you are doing now is adding a new variable list to the state.

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

1 Comment

thanks! I totally didn't catch that when seeing it the first time but now its obvious
2

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,
};

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.