This question is just related to reducing the code complexity. I have 8 arrays, in which I have to add items based on a button click. what I did is make 8 separate functions for all these tasks. is there any solution to combine all these functions into a single function that accepts an array as a parameter and does the rest of the job?
const [deleteArray,setDeleteArray]=useState([]);
const [newArray,setNewArray]=useState([]);
const handleDeleteParking = (id) => {
setDeleteArray((deleteArray) => [...deleteArray, id]);
}
const handleNewParking = (id) => {
setNewArray((newArray) => [...newArray, id]);
}
I have a total of 8 arrays with 8 separate functions to add items to the array, how can I achieve this task with a single function.
CodePudding user response:
You can't just pass the array into the function, since the array and the setArray
function are different. But you can of course pass in the setter function instead:
const addToArray = (id, setStateFn) => {
setStateFn((arr) => [...arr, id]);
}
// usage: instead of handleDeleteParking(id)
addToArray(id, setDeleteArray);
CodePudding user response:
You could have created an object that will store all your values.
Check the below code that may help you.
const [data, setData] = useState({
deleteParking: [],
newParking: [],
});
const handleChange = (key, id) => {
setData(prev => {
return {
...prev,
[key]: [
...prev[key],
id,
]
}
});
}
handleChange('deleteParking', 1);
handleChange('newParking', 1);
CodePudding user response:
You can merge all of your state into one state and then you can create common function to update particular state and then along with array( updated array ) you can pass the property name . Like this
const [arrState,setArrayState]=useState({deleteArr:[]});
const commonUpdateFunction=(id, propertyName)=>{
setArrayState (prev=> ({...prev,[propertyName]:[...prev.[propertyName],id]}))
}
On click
const handleClick=(someId)=>{ commonUpdateFunction(someId,deleteArr) }