Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
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}
/>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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];
    });
};
about 4 years ago · Juan Pablo Isaza Report

0

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)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!