Here how I’m trying to add some values to my data. The problem is that the tasks add as an object in the same level as parent’s object. Like this:
However, I need it to be inside an object.
// This is my data const [list, setList] = useState({ home: { title: "Home", color: "#5786ff", icon: <MdContentPaste />, tasks: [ { note: "Play Basketball", time: "21:00", }, ], }, work: { title: "Work", color: "#ffc93c", icon: <MdMailOutline />, tasks: [ { note: "Write Essay", time: "2:00" }, ], }, }); // Here I am trying to add the notes to my tasks const [noteInput, setNoteInput] = useState(""); const [noteTime, setNoteTime] = useState(""); const handleSubmit = () => { setList({ ...list, tasks: [...list[listName].tasks, { note: noteInput, time: noteTime }], }); }; // Explanation (...list[listName].tasks) - takes the parent object's tasks
Advertisement
Answer
The listName
looks to be the top level property, so use that to add another level:
setList({ ...list, [listName]: { ...list[listName], tasks: [...list[listName].tasks, { note: noteInput, time: noteTime }], }, });