【问题标题】:my useFetch custom hook is giving me infinite loopmy useFetch custom hook is giving me infinite loop
【发布时间】:2022-12-02 00:14:14
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs url get


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 1970-01-01
      • 2022-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多