Quiero que mi identificación aumente cada vez que se ejecuta esta función, pero cuando consuelo, la identificación del objeto vuelve indefinida
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) };Componente
<NotesList notes={notes} handleAddNote={addNote} handleDeleteNote={deleteNote} />Creo que no necesitas count el estado.
En su lugar, pruebe la función de actualización useState como esta:
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]; }); };establecer el estado no devuelve nada, por lo que inicializar a ID es incorrecto. En su lugar, puede asignar su identificación de esta manera
const newNote = { id: count+1, text: text, date: date.toLocaleDateString(), }; setCount(count+1)