Reputation: 2439
I have a CRUD functionality in my react application using hooks and es6. I'm using AntDesign List Component as well. In my add function, after adding for the first time, it's expected that it's been added on the list.
But after creating another one, it's just replacing the existing array. It's not been added like index 1. It's always index 0.
Here's my code
const leaveTypeList = [];
const [isLeaveType, setLeaveType] = useState(leaveTypeList);
useEffect(() => {
setLeaveType(leaveTypeList);
}, [setLeaveType]);
const payload = {
leaveTag: values.leaveTag,
leaveTagColor: values.leaveTagColor,
hexCode: state.tagColor,
dateCreated: formatLeaveTypeDate,
};
leaveTypeList.push(payload);
setLeaveType(leaveTypeList);
Upvotes: 0
Views: 116
Reputation: 31
hey since you need to add a new item to array there is no need of the useEffect hook
const leaveTypeList = [];
const [isLeaveType, setLeaveType] = useState(leaveTypeList);
const payload = {
leaveTag: values.leaveTag,
leaveTagColor: values.leaveTagColor,
hexCode: state.tagColor,
dateCreated: formatLeaveTypeDate,
};
setLeaveType([...isLeaveType,payload]);
you can simple use setter to set new state updating the existing array by adding the new payload to it.
Upvotes: 2
Reputation: 389
You should push the new data by isLeaveType.push(payload)
.
Also,
useEffect(() => {
setLeaveType(leaveTypeList);
}, [setLeaveType]);
makes no sense to me.
Since the setLeaveType
is the setter for isLeaveType
, there is no reason for the effect to depend on it.
Upvotes: 1