React useEffect update variable API call inifite loop

27 Views Asked by At

Successfully updating database, calling the API will refresh the component on page when clicked - Works when adding variable to the useEffect but causes and inifite loop.

When removing featured from useEffect and leaving [] it stops the inifinite loop but page doesn't update. Any thoughts?

export const App = () => {
    const [featured, setFeatured] = useState([]);

    const fetchData = async () => {
        try {
            const response = await getAllFeatured();
            const getFeatured = response.data.map(data => data)
            setFeatured(getFeatured);
        } catch (err) {
            console.log(err);
        }
    }

    useEffect(() => {
        fetchData();
    }, [featured]);

1

There are 1 best solutions below

1
twharmon On

Does this help? You should use useCallback to preserve the referential identity of fetchData. Then, it can safely be used in the dependency array.

export const App = () => {
    const [featured, setFeatured] = useState([]);

    const fetchData = useCallback(() => {
        const go = async () => {
            try {
                const response = await getAllFeatured();
                const getFeatured = response.data.map(data => data)
                setFeatured(getFeatured);
            } catch (err) {
                console.log(err);
            }
        };
        go();
    }, []);

    useEffect(() => {
        fetchData();
    }, [fetchData]);