简体   繁体   中英

React - Problem with update state (useState) in onChange function

I'm having a problem updating the state on a handleItemChange function for a form. Do you have a solution? thank you so much...

const [items, setItems] = useState([]);

const addPrestation = () => {

    const id = Date.now().toString();
    const prestation = {...items};
    prestation[id] = {
        customer:customer,
        id: id,
        delivery: "",
        quantity: "",
        unit: "",
        unitPrice: "",
        tva: "",
        htAmount: "",
        ttcAmount: ""
    }
    setItems([...items, {prestation:prestation}])
}

 const handleItemChange = (event, prestation, field ) => {
   const value = event.target.value;
   const clonePresta = {...prestation};
   clonePresta[field] = value;
   const clonePrestations = {...items};
   clonePrestations[clonePresta.id] = clonePresta;

   setItems(???)
}

I think you should do something like that:

const handleItemChange = (event, prestation, field ) => {
   const value = event.target.value;
   const clonePresta = {...prestation};
   clonePresta[field] = value;
   const clonePrestations = {...items};
   clonePrestations[clonePresta.id] = clonePresta;

   setItems([...items, {presentation: clonePresta})
}
const handlePrestaChange = ({currentTarget}) => {
    const {name, value, id} = currentTarget;
    const clonePresta = {...prestation}
    clonePresta[name] = value;
    setPrestation({...prestation, [name]: value })
    const tabItems = [...items];
    tabItems[id] = clonePresta;
    setItems([...tabItems])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM