First, please look at the code.
const [currentUserPK, setCurrentUserPK] = useState(undefined);
const [currentPage, setCurrentPage] = useState(1);
const [rowsPerPage, setRowsPerPage] = useState(10);
//현재 USER_PK 가져오는 API
const getCurrentUserPk = async () => {
const url = '/api/account/decoding-token';
const res = await get(url)
.then((res) => {
console.log(res);
setCurrentUserPK(res.data.USER_PK);
})
.catch((error) => {
console.log(error);
});
};
useEffect(() => {
getCurrentUserPk()
},[]);
//생성된 액션 아이템 불러오기 API
const getActionItems = async () => {
const url = `/api/work/view-items`;
const params = {
id: currentUserPK,
currentPage: currentPage,
feedsPerPage: rowsPerPage,
};
await get(url, { params: params }).then((res) => {
setActionItemArray(res.items);
console.log(res.items);
console.log(actionItemArray);
});
};
useEffect(() => {
getActionItems();
}, [currentPage, rowsPerPage, actionItemArray]);
The problem happens with this following code.
useEffect(() => {
getActionItems();
}, [currentPage, rowsPerPage, actionItemArray]);
When I add actionItemArray in the second argument array, It keeps looping
console.log(res.items);
console.log(actionItemArray);
these two console.log events.
When I delete actionItemArray from the second argument of useEffect Hook, I have to refresh my page to added, deleted and edited actionItems.
I have no idea why it happens. Please help!
CodePudding user response:
"dependencies" (second argument) of the useEffect
means the values change should trigger "the effect" (first argument)
Inside effect, you change the actionItemArray
, which is also passed into dependencies.
CodePudding user response:
The useEffect
is calling a function that is changing state: setActionItemArray()
. Changing state triggers another render which will in turn call the useEffect
again starting the process over.
useEffect
runs on the initial render, and then because of the way you have it implemented, will run whenever one of the dependencies in the array changes. So since it is running when the page first loads, it is starting it's infinite loop on every page load