skip to Main Content

I am fetching a data from an API and setting a state. When I do that process, It makes get requests each millisecond. This problem happens, if I set the dependencies array. I want to make a request when API is updated.

  const [products, setProducts] = useState({ baskets: [] });

  useEffect(() => {
    fetch("/api")
      .then((response) => response.json())
      .then((products) => {
        setProducts(products);
      });
  }, [products]);

3

Answers


  1. Remove the dependency from the useEffect Hook

     useEffect(() => {
        fetch("/api")
          .then((response) => response.json())
          .then((products) => {
            setProducts(products);
          });
      }, []);
    

    Here you are updating results into setProducts and it triggers products state change due to useEffect behaviour, So it’ll be called infinety.
    Also I suggest you to change

    .then((result) =>{
       setProducts(result);
    })
    

    Here, you’ll face issues with scope in products.

    So your final could should be this :

    useEffect(() => {
        fetch("/api")
          .then((response) => response.json())
          .then((result) => {
            setProducts(result);
          });
      }, []);
    

    Also As per your below comment, here is the updated sample code with use of useCallback

    const [products, setProducts] = useState({ baskets: [] });
    
      const fetchProdcuts = useCallback(() => {
        fetch("/api")
          .then((response) => response.json())
          .then((result) => {
            setProducts(result);
          });
      }, []);
    
      useEffect(() => {
        fetchProdcuts();
      }, [fetchProdcuts]);
    
    

    ** call fetchProdcuts method whenever you need to refresh the product lists**

    Hope it helps!

    Login or Signup to reply.
  2. You’re trying to fetch data from the API and update products with the API response. The implementation is correct, but it’s causing an infinite loop.

    The loop occurs because the useEffect dependency array includes products, signifying that the useEffect should be triggered whenever products change.

    Here’s how the loop unfolds:

    1. The component mounts, triggering the useEffect.
    2. The fetch call inside the useEffect retrieves data and updates
      products.
    3. The useEffect notices that products has changed (due to its presence
      in the dependency array), causing it to run again.
    4. The loop repeats, leading to continuous API requests.

    To break this loop, you should remove products from the useEffect dependency array. By doing so, the useEffect will execute only when the component mounts, avoiding subsequent triggers caused by state changes

      const [products, setProducts] = useState({ baskets: [] });
    
      useEffect(() => {
        fetch("/api")
          .then((response) => response.json())
          .then((products) => {
            setProducts(products);
          });
      }, []);
    

    You can read more about useEffects in the docs.

    Login or Signup to reply.
  3. const [products, setProducts] = useState({ baskets: [] });
    
    useEffect(() => {
      fetch("/api")
        .then((response) => response.json())
        .then((fetchedProducts) => {
          setProducts(fetchedProducts);
        });
    }, []);
    
    const updateProducts = () => {
      fetch("/api")
        .then((response) => response.json())
        .then((updatedProducts) => {
          setProducts(updatedProducts);
        });
    };
    

    Try like this

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search