Home > OS >  the previous state is not saved - React useatate
the previous state is not saved - React useatate

Time:08-24

I'm trying to save objects to an array, but I can't do it, the old state is deleted. I have two states in my component, from two different forms, the first form is just text and I get the data by "handleChange", but the second form is several objects that I want to store in an array that I get by "handleChangeArray".

const [formCompra, setFormCompra] = useState({
        name: '',
        lastName: '',
        items: []
});

const [restForm, setRestForm] = useState();

const handleChage = (e) => {
        const { name, value } = e.target;
        setFormCompra({
            ...formCompra,
            [name]: value
        })
}
 
const handleChangeArray = (e) => {
        const { name, value } = e.target;
        setRestForm({
            ...restForm,
            [name]: value
        })
}

const handleSubmit = () => {

        let newData = {
            name: formCompra.name,
            lastName: formCompra.lastName,
            items: [...formCompra.items, restForm] //probably the error is here
        }

        console.log(newData)

}   

As I mention, it is not possible to save the data in the array, I appreciate any help.

CodePudding user response:

You can use the current state to set a new value, keeping all other values:

setState((current) => ({
  ...current,
  key: newValue
}));

CodePudding user response:

What I would do is:

const [formCompra, setFormCompra] = useState({
        name: '',
        lastName: '',
        items: []
});

const [restForm, setRestForm] = useState();

const handleChage = (e) => {
        const { name, value } = e.target;
const temp_compra = {...formCompra};
temp_compra[name] = value;
        setFormCompra({
            ...temp_compra
            
        });
}
 
const handleChangeArray = (e) => {
        const { name, value } = e.target;

        const temp_form = {...restForm};
temp_form[name] = value;
        setRestForm({
            ...temp_Form
            
        });
}

const handleSubmit = () => {

        let newData = {
            name: formCompra.name,
            lastName: formCompra.lastName,
            items: [...formCompra.items, restForm]
        }

        console.log(newData);
return newData

}   

And use handleSubmit like this

 const newData = handleSubmit();

CodePudding user response:

I think the issue may be that spread syntax only shallow copies the array, so in

const handleSubmit = () => {

    let newData = {
        name: formCompra.name,
        lastName: formCompra.lastName,
        items: [...formCompra.items, restForm] //probably the error is here
    }

items is a copy of an array that points to all the original objects. try

let newData = {
        name: formCompra.name,
        lastName: formCompra.lastName,
        items: [...formCompra.map(x=>{...x}), {...restForm}] //probably the error is here
    }
  • Related