I'm new to react and wanted to know how to update and edit the array data in the same function handleSubmit() from the forms in react by applying conditions
This is my code
const Subcontentinfo = () => {
const [contacts, setContacts] = useState([
{ id: 1, firstname: "Mike", lastname: "Huston", surname: "MH", mailid: "[email protected]", company: "Estra Boutique ltd." },
{ id: 2, firstname: "Richard", lastname: "", surname: "R", mailid: "[email protected]", company: "Amazonia online" },
{ id: 3, firstname: "James", lastname: "Dustin", surname: "JD", mailid: "[email protected]", company: "Alibaba Traders .co" },
{ id: 4, firstname: "Amanda", lastname: "Paul", surname: "AP", mailid: "[email protected]", company: "Estra Boutique ltd." }
]);
const [addFormData, setAddFormData] = useState({
firstname: "",
lastname: "",
surname: "",
mailid: "",
company: "",
});
const [editContactId, setEditContactId] = useState(null);
const addData = () =>{
const newContact = {
id: contacts.length 1,
firstname: addFormData.firstname,
lastname: addFormData.lastname,
mailid: addFormData.mailid,
company: addFormData.company
}
setAddFormData({
firstname: "",
lastname: "",
mailid: "",
company: "",
setContacts([...contacts, newContact]);
});
}
editData(){
const editedContact = {
id: editContactId,
firstname: addFormData.firstname,
lastname: addFormData.lastname,
mailid: addFormData.mailid,
company: addFormData.company,
};
const newContacts = [...contacts];
const index = contacts.findIndex((contact) => contact.id === editContactId);
newContacts[index] = editedContact;
setContacts(newContacts);
setEditContactId(null);
}
I want addData() and editData() to be in same method(like handleSubmit()) by applying condition This is my button:
<button type="submit" onClick={handleSubmit} className="data-saving" >Save</button>
CodePudding user response:
I suggest rather than using two different State you can use only one state and do something like that
const [formData, setFormData] = useState({
id: null
firstname: "",
lastname: "",
surname: "",
mailid: "",
company: "",
});
handleSubmit(formObject){
if(formData.id === null){
// if "id" is null its mean its a new record
//... create the unique ID here
}else{
// edit the existing record and update
}
}
CodePudding user response:
In order to update current values in your state you should use array or object destructing based on how you stored data. In case you have array of objects
const [contacts, setContacts] = useState([
{name: "John", age: 20},
{name: "Dastn", age: 25}
])
To update it (to add {name: "Doe", age:30}
)
const onSubmit = newObject => {
setContacts(prevState => [...prevState, newObject])
}
After that your contacts
array will become like this:
[
{name: "John", age: 20},
{name: "Dastn", age: 25},
{name: "Doe", age:30}
]