Reputation: 123
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?
Upvotes: 7
Views: 6582
Reputation: 86
You should only call fetch when components mounts. Since you are using hooks, you should use `
useEffect(()=> {
fetch("http://localhost:5000/products")
.then((res) => res.json())
.then((res) => {setProducts(res)})
.catch((err) => console.error(err))
}, [])
`
What you are doing right now, is calling fetch on every render. Imagine it like this. You are rendering the component, during that you are fetching something and updating the state. When the state updates, it rerenders the components and you are going on an infinite loop.
Upvotes: 4
Reputation: 1669
the problem is in {setProducts(res)}
this will update the state and re-render the component then call the fetch function second time and so on
Upvotes: 0