Home > other >  why useState in this code does not unpdate id (the text does updated but not id)?
why useState in this code does not unpdate id (the text does updated but not id)?

Time:12-01

I am trying to increment the ID value useing the useState hook,but its not incrementing .I have to call the fct two times for the id to be incremented.I was able to see that by console log the object before and after the usestate but i found the result the same

function ToDoListApp() {
    const [noteList, setNoteList]=useState([])
    const [note,setNote]=useState({ noteId: 0 , txt: "", noteState: false })
    function addToList(e) {
        e.preventDefault();
        if(noteList.length===0){
            console.log(note)
            setNote({noteId: 0 , txt: note.txt ,noteState: false })
            setNoteList(noteList=>[...noteList,note])
        }else{
            console.log(note)
            console.log(noteList[noteList.length-1].noteId   1)
            setNote({noteId:noteList[noteList.length-1].noteId   1,txt:note.txt, noteState:false})
            setNoteList(noteList=>[...noteList,note])
            console.log(note)
            
        }
          
    }
    function deleteItemFromList(e,id){
        
        setNoteList(noteList.filter(note => note.noteId !== id ))
        console.log(noteList.length)
    }
    function handleTheNoteTxt(e) {
        e.preventDefault();
        setNote({
            ...note,
            txt:e.target.value
        })
        
      }


    const notesDiplay =noteList.map((note)=>
    <Stack key={note.noteId} direction="row" className="note-styling" justifyContent="center" alignItems="center" spacing={2}>
        <p>{note.txt} </p>
        <p>{note.noteId} </p>
        
        <Button onClick={e => deleteItemFromList(e,note.noteId)} variant="outlined" size='small' >X</Button>
        
    </Stack>
    )
  return (
    <div>
        <Stack direction="column" justifyContent="center" alignItems="center">
        <Stack className='note-app-container bg1' direction="column" justifyContent="flex-start" alignItems="center" spacing={2} >
            <div className='notes-input bg3'>
                <TextField autoFocus  label="Add your note" variant="standard" value={note.txt} 
                    onChange={handleTheNoteTxt}/>
                <Button variant="outlined" size='medium' onClick={addToList}>Add</Button>
            </div>
            <div className='notes-container bg3'>
            {notesDiplay}
            </div>
        </Stack>
        </Stack>     
    </div>
  )
}

export default ToDoListApp`

CodePudding user response:

The link that Christian sent is useful for you to understand what's going on.

This is one way to solve it:

function addToList(e) {
    e.preventDefault();
    if (noteList.length === 0) {
      const newNote = { noteId: 0, txt: note.txt, noteState: false };
      setNote(newNote)
      setNoteList([...noteList, newNote])
    } else {
      const newNote = { noteId: noteList[noteList.length - 1].noteId   1, txt: note.txt, noteState: false };
      setNote(newNote)
      setNoteList([...noteList, newNote])
    }
  }

CodePudding user response:

Here is a fixed version with a little simplifying and refactoring.

import { useState } from 'react';
import { Stack, Button, TextField } from '@mui/material'

function ToDoListApp() {
    const [noteList, setNoteList] = useState([]);
    const [nextId, setNextId] = useState(1);
    const [value, setValue] = useState("")


    function addToList(e) {
        e.preventDefault();
        noteList.push({
            noteId: nextId,
            txt:  value,
            noteState: false
        })
        setNextId(val => val   1);
        setValue("");
    }


    function deleteItemFromList(e, id) {

        setNoteList(noteList.filter(note => note.noteId !== id))
        console.log(noteList.length)
    }


    const notesDiplay = noteList.map((note) =>
        <Stack key={note.noteId} direction="row" className="note-styling" justifyContent="center" alignItems="center" spacing={2}>
            <p>{note.txt} </p>
            <p>{note.noteId} </p>
            <Button onClick={e => deleteItemFromList(e, note.noteId)} variant="outlined" size='small' >
                X
            </Button>
        </Stack>
    )

    return (
        <div>
            <Stack direction="column" justifyContent="center" alignItems="center">
                <Stack className='note-app-container bg1' direction="column" justifyContent="flex-start" alignItems="center" spacing={2} >
                    <div className='notes-input bg3'>
                        <TextField autoFocus label="Add your note" variant="standard"
                            onChange={(e) => setValue(e.target.value) } />
                        <Button variant="outlined" size='medium' onClick={addToList}>Add</Button>
                    </div>
                    <div className='notes-container bg3'>
                        {notesDiplay}
                    </div>
                </Stack>
            </Stack>
        </div>
    )
}

export default ToDoListApp
  • Related