Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React simple fetch program run into an infinite loop

I have a simple program which receives some JSON data from a node backend and set received data into state. The problem is it reset state infinite times, creating an infinite rendering.

Here is the JSON data

[
  {
    "id": 1,
    "name": "Product 1",
    "category": "C1",
    "price": "100"
  },
  {
    "id": 2,
    "name": "Product 2",
    "category": "C1",
    "price": "80"
  },
  {
    "id": 3,
    "name": "Product 3",
    "category": "C3",
    "price": "120"
  }
]

Here is the react program.

import React, { useState } from 'react'

const MainApp = () => {
    const [products, setProducts] = useState([])

    fetch("http://localhost:5000/products")
        .then((res) => res.json())
        .then((res) => {setProducts(res)})
        .catch((err) => console.error(err))
    
    console.log("Products:",products) //This keep getting logged forever.

    return (
        <h1>Test</h1>
    )
}

export default MainApp

What have I done wrong?

like image 850
Rockt Avatar asked Jul 26 '26 07:07

Rockt


1 Answers

The fetch is continuously performed on every render of MainApp. Consider using an effect to solve this.

like image 88
user3882 Avatar answered Jul 28 '26 19:07

user3882



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!