I have 1 input:
<input
type="text"
name={item.job_n}
defaultValue={item.azienda}
readOnly={isReadonly}
onChange={handleChange}
And onChange I'm adding the inputs value and name as an Object to an array of Objects in useState=([]), therefore my array looks like this: [{azienda:'', job_n:''}, {azienda:'', job_n:''}]
const [azienda, setAzienda] = useState([]);
const handleChange =(e)=>{
{
const azienda_name = e.target.value
const job_n = e.target.name
setAzienda((prevState) => [...prevState, {azienda: azienda_name, job_n: job_n}])
}
}
The code works fine and a new Object is added to my array each time an onchange event occurs. The issue I'm having is that if an object with job_n already exists in the array I'd need to update that object and not create a new object for each onchange.
CodePudding user response:
I have changed the variables from italian to english so that everyone can understand them, and also changed some variables to follow the javascript naming conventions.
function handleChange(e) {
const businessName = e.target.value;
const jobName = e.target.name;
const jobIndex = business.findIndex(v => {
return v["jobName"] === jobName;
});
if (jobIndex === -1) {
setBusiness([...business, { businessName, jobName }]);
return;
}
const businessClone = [...business];
businessClone[jobIndex] = { businessName, jobName };
setBusiness(businessClone);
}
CodePudding user response:
Change your code to,
setAzienda((prevState) => {
const jobExistIndex = prevState.findIndex(obj => obj.job_n === job_n)
const jobExist = prevState[jobExistIndex]
if (jobExist) {
const newState = [...prevState]
newState[jobExistIndex] = {...jobExist, job_n: job_n}
return newState
}
else {
const newState = [...prevState]
return [...newState, {azienda: azienda_name, job_n: job_n}]
}
CodePudding user response:
const handleChange = e =>{
{
const azienda_name = e.target.value;
const job_n = e.target.name;
const existIndex = azienda.findIndex(p => p.job_n === job_n);
if(existIndex != -1)
{
azienda[existIndex].azienda_name = azienda_name
}
else
{
azienda.push({azienda_name : azienda_name, job_n: job_n})
}
setAzienda(azienda);
}