Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

my useFetch custom hook is giving me infinite loop

**the code below is my context which I am using useFetch **
**when i change the url with changing the searchTerm **
** i am getting an infinite loop **

import React, { useContext, useState, useEffect } from "react";
import { useFetch } from "../hooks/useFetch";
const context = React.createContext();

const AppProvider = ({ children }) => {
    let url = " https://www.thecocktaildb.com/api/json/v1/1/search.php?s=";
    let [searchTerm, setSearchTerm] = useState("a");

    useFetch(`${url}${searchTerm}`);


    setSearchTerm('s');


    return <context.Provider value={"hello"}>
        {children}
    </context.Provider >

}

const useGlobal = () => {
    return useContext(context);
}

export { AppProvider, useGlobal };

** the code below is my custom hook useFetch**

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { useEffect, useState } from "react";
export const useFetch = (url) => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);

    const getData = async () => {
        try {
            const response = await fetch(url);
            const jsonResponse = await response.json();
            setData(jsonResponse);
            setLoading(false);
        } catch (err) {
            console.log(err);
        }

    }
    useEffect(() => {
        getData();
    }, [url])

    return { data, loading };
}

`

I tried to change the search Term like this
searchTerm="h"
and it works perfectly but when i change searchTerm with setSearchTerm it gives me infinite loop

>Solution :

setSearchTerm('s'); inside a useEffect

const [url] = useState(" https://www.thecocktaildb.com/api/json/v1/1/search.php?s=");
const [searchTerm, setSearchTerm] = useState("a");

const  { data, loading } = useFetch(`${url}${searchTerm}`);

useEffect(() => {
      setSearchTerm('s');
}, [])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading