skip to Main Content
const [addData,setAddData]=useState({
        title:"",
        state:"incomplete",
        index:0
    })

function handleAddPage(event){
        setAddData((prev) =>{
          return {...prev,[event.target.name]:event.target.value}
        })
      }

function AddHandler(event){
        event.preventDefault();
        const uniq=uuid();
        setAddData((prev)=>({
            ...prev,[state]:uniq
        }));
        setAll([...all,addData]);
        if(addData.state==="complete")
        setComplete([...complete,addData]);
        else if(addData.state==="incomplete")
        setIncomplete([...incomplete,addData]);   
    }

I am trying to pass unique id’s with each task.But , 0(default) is being allocated to each task.

2

Answers


  1. The issue you are facing is due to the asynchronous nature of the state updates in React. When you call setAddData to update the addData state with the unique ID, the addData state has not yet been updated with the new value when you add it to the arrays (all, complete, incomplete).

    function AddHandler(event) {
      event.preventDefault();
      const uniq = uuid();
    
      // Create a copy of 'addData'
      const tempData = { ...addData, state: uniq };
    
      setAddData((prev) => ({
        ...prev,
        state: uniq,
      }));
    
      // Update the arrays with the updated 'addData'
      setAll([...all, tempData]);
      if (addData.state === "complete") {
        setComplete([...complete, tempData]);
      } else if (addData.state === "incomplete") {
        setIncomplete([...incomplete, tempData]);
      }
    }
    
    
    Login or Signup to reply.
  2. Here’s my solution.

    import { v4 as uuidv4 } from 'uuid';
    
    function AddHandler(event) {
      event.preventDefault();
      const uniq = uuidv4(); // Generate a unique ID using uuidv4()
      const newData = {
        ...addData,
        state: uniq, // Assign the unique ID to the 'state' property
      };
      setAddData(newData);
      setAll([...all, newData]);
      if (newData.state === "complete") setComplete([...complete, newData]);
      else if (newData.state === "incomplete") setIncomplete([...incomplete, newData]);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search