Skip to content
Advertisement

Why does this GET request create infinite loop? (React)

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!

Advertisement

Answer

“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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement