Alyssa Reyes
Alyssa Reyes

Reputation: 2439

Adding new object in array in existing array

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.

enter image description here

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.

enter image description here

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);

enter image description here

Upvotes: 0

Views: 116

Answers (2)

Hashan Eranda
Hashan Eranda

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

Harry Chang
Harry Chang

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

Related Questions