0

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@AlyssaReyes Not just a good suggestion, this is actually the correct answer. You should not mutate state so the accepted answer shows a lack of knowledge about React. Here is a reference.
@HMR Hello. I actually change my code that suggested here. But since Harry Chang first commented and tried his solution, it worked on my end. So I think I'm being fair with him accepting his answer :)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.