'React state returns undefined when passed as object value
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}
/>
Solution 1:[1]
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)
Solution 2:[2]
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];
});
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rahul R S |
| Solution 2 | Mereke |
