Home > database >  my useFetch custom hook is giving me infinite loop
my useFetch custom hook is giving me infinite loop

Time:12-02

**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**

`

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

CodePudding user response:

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');
}, [])
  • Related