I want my id to be increased every time this function is executed,but when I console the object id returns undefined
let [count, setCount] = useState(0);
const addNote = (text) => {
const date = new Date();
const newNote = {
id: setCount(count++),
text: text,
date: date.toLocaleDateString(),
};
const newNotes = [...notes, newNote];
setNotes(newNotes);
console.log(newNotes)
};
Component
<NotesList notes={notes}
handleAddNote={addNote}
handleDeleteNote={deleteNote}
/>
I think you don't need count state.
Instead try useState updater function like this:
const addNote = (text) => {
setNotes(prevNotes => {
const prevId = prevNotes[notes.length - 1].id;
const date = new Date();
const newNote = {
id: prevId + 1,
text: text,
date: date.toLocaleDateString(),
};
return [...prevNotes, newNote];
});
};
set state does not return anything, So initialising to ID is wrong. Instead you can assign your id like this
const newNote = {
id: count+1,
text: text,
date: date.toLocaleDateString(),
};
setCount(count+1)