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?
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?
useEffect
hook with an empty dependency to make sure it is only called once at the initial render of the ponent. You can read about useEffect
here: reactjs/docs/hooks-effect.html
– Israel Obanijesu
Commented
Mar 14, 2021 at 7:44
The fetch is continuously performed on every render of MainApp. Consider using an effect to solve this.
You should only call fetch when ponents 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 ponent, during that you are fetching something and updating the state. When the state updates, it rerenders the ponents and you are going on an infinite loop.
the problem is in {setProducts(res)}
this will update the state and re-render the ponent then call the fetch function second time and so on