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?
useEffecthook with an empty dependency to make sure it is only called once at the initial render of the component. You can read aboutuseEffecthere: reactjs.org/docs/hooks-effect.html