7

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?

1
  • 1
    you keep calling fetch everytime the component is re-rendered, when you update a state in React, the component gets re-rendered, and everything in the whole function is called again, you should put fetch into a useEffect hook with an empty dependency to make sure it is only called once at the initial render of the component. You can read about useEffect here: reactjs.org/docs/hooks-effect.html Commented Mar 14, 2021 at 7:44

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

why is mainapp rerendering so much?
5

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.