I am using react functional component and i have state which stores array
const [channelList, setChannelList] = useState([]);
This function updates the state after submisson of an input form and state updates sucessfully
const handleFormSubmit = (event) => {
event.preventDefault();
const channelName = inputChannelNameRef.current.value;
const channelId = inputChannelIdRef.current.value;
setChannelList([
...channelList,
{
rowId: channelList.length 1,
channelName: channelName,
channelId: channelId,
template: deleteBtn, // delete button component which perform row delete action
},
]);
console.log(channelList.length);
};
This function is called on clicking the delete button through passing row ID
const deleteRow = (rowId) => {
console.log(channelList.length); // logging zero every time
}
This deleteRow() function was not working so i console.log the state length then i found that it is returning 0 every time but my rows are showing perfectly fine. Why it is giving zero when it has number of objects in it. In function handleFormSubmit() i am getting length of channelList perfectly fine.
CodePudding user response:
Try to use prev:
const obj = {
rowId: channelList.length 1,
channelName: channelName,
channelId: channelId,
template: deleteBtn,
},
setChannelList((prev) => {...prev,...obj})
CodePudding user response:
State changes are asynchronous, so they will not show on a console.log immediately.
If you want to check length of the state by logging it to the console, you can place your console.log in a useEffect hook with your state as the dependency.
This will log the state array length every time channelList is set.
It is a bit strange you aren't seeing the length on the deleteRow Function, unless you are setting state immediately before the console.log.
Edit: reading again, you shouldn't be seeing an updated channelList.length when trying to log it in handleFormSubmit. You are likely seeing the length prior to the state change.
useEffect(() => {
console.log(channelList.length);
}, [channelList])