4

I am trying to make a Todo app using React.js.

I took todo data from an in-app js file as a JSON object. I want to add more todo in my list which I want to store in that js file as a JSON object.

I want to append another JSON object with existing. How can I do it?

TodoList.js file

const TodoList=
   [

    {
      "id": 1,
      "title": "Learn backbone",
      "complete": false,
      "canceled": false,
      "date": new Date().getTime()
    },

    {
      "id": 2,
      "title": "Go for a run",
      "complete": false,
      "canceled": false,
      "date": new Date().getTime()
    }
  ]

  export default TodoList;

New TodoList.js file should be like this:

const TodoList=
[

    {
      "id": 1,
      "title": "Learn backbone",
      "complete": false,
      "canceled": false,
      "date": new Date().getTime()
    },

    {
      "id": 2,
      "title": "Go for a run",
      "complete": false,
      "canceled": false,
      "date": new Date().getTime()
    },

    {
      "id": 3,
      "title": "Have Lunch",
      "complete": true,
      "canceled": false,
      "date": new Date().getTime() 
    }
  ]

  export default TodoList
1
  • 1
    Your TodoList const is an array. You can either use spread operator or use TodoList.push(newTodo). This is more of a Javascript question than a react tho. Commented Sep 22, 2019 at 10:48

1 Answer 1

8

This has nothing to do with React, this is plain object/array manipulation in Javascript. If you want to take an existing array and add a new element, simply have:

const newToDoList = [...toDoList, {"id": 3, ...}]

You spread the previous array and create a new one with a new element.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.