samedi 26 juin 2021

How can I add a new item and render it without the timeout? React

I have this code, basically is for adding a new item to a list.

import './styles/app.css'
import {useState, useEffect} from 'react'


const initialList = [
  {title: 'Group 1', items: ['Item 1', 'Item 2', 'Item 3']},
  {title: 'Group 2', items: ['Item 1', 'Item 2']}
]

function App() {

  const [dale, setDale] = useState(true);
  const [list, setList] = useState(initialList);
  
  const handleAdd = (e)=>{
    setDale(false);
    const newList = list;
    newList[e.target.parentNode.id-1].items.push('New');
    setList(newList);
    setTimeout(() => {
      setDale(true);
    }, 1);
    
  }

  return (<div>{dale ? <div className="App" key="app">
  {list.map((group, groupI)=>{
    return (
      <div id={groupI+1} key={groupI+1} className="dnd-group">
          <div className="dnd-title">{group.title}</div>
          {group.items.map((item, itemI)=>{
            return(
              <div draggable key={itemI+1}className="dnd-item">
                Item {itemI+1}
              </div>)
          })}
          <div className="dnd-añadir-item" onClick={handleAdd}>Add</div>
        </div>
        )
        })}
      </div>:<div>No vuic</div> }</div>
  );
      
}



export default App;

If I delete the timeout function and the 'dale' state the list keeps updating itself but is not updated in the render. I want to know how to render the updated list without this absurd timeout and 'dale' state.




Aucun commentaire:

Enregistrer un commentaire