Home > Software design >  'Maximum update depth exceeded' error when trying to use custom function passed as props i
'Maximum update depth exceeded' error when trying to use custom function passed as props i

Time:04-14

I am trying to use a pass a function as props declared in App.js to handle a state variable in App.js in order to add items to a cart component but get this error as soon as I add the function to the onClick field of the "Add" button in my product component(at the end of post):

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

My App.js looks like this:

const App = () =>  {
  const [cartItems, setCartItems] = useState([]);

  const handleAddProduct = (product) => {
 //some logic to add product to cartItems list here
  }
   return(
      <Box className="App">
      <AppRoutes handleAddProduct={handleAddProduct} cartItems={cartItems}/>
      </Box>
   );
}

Im passing the function and the state variable as props to my routes component so I can access it in my Products page:

const AppRoutes = ({ handleAddProduct, cartItems }) => {
    return (
            <Routes>
                <Route exact path="/alldrip" element={<ProductsPage handleAddProduct={handleAddProduct} />} />       
            </Routes>
    )}

And in my products page the function gets passed as props again to another component:

const ProductsPage = ({ handleAddProduct }) => {
 return (
        <AllProducts handleAddProduct={handleAddProduct} />
  )} 

And then I pass the function one last time in AllProducts to an individual Product component: ( I seperated the components this way so it is easier for me to read)

const AllProducts = ({ handleAddProduct }) => {
return (
        {products.map(product => {
          return (
              <Product handleAddProduct={handleAddProduct} product={product} />
          )
        })}
  )}

The products load fine but the app crashes with the error as soon as I add the function to the "Onclick" of the add to cart button:

const Product = ({ handleAddProduct, product }) => {
   return (
           <Heading>{product.name}</Heading>
           <Text >{product.material}</Text>
           <Text>{product.price} </Text>
           <Button onClick={handleAddProduct(product)}  >Add to Cart</Button>
    )}

If I remove the function the app stays alive !

I'm not understanding why the error states setState is getting called repeatedly.

CodePudding user response:

onClick={handleAddProduct(product)}

This should probably only be

onClick={() => handleAddProduct(product)}

otherwise you're calling the handleAddProduct method on render directly and not on click.

CodePudding user response:

You call your handleAddProduct directly in your jsx that re-renders the component that directly call handleAddProduct and so on ...

You can try

onClick={() => handleAddProduct(product)}

A better approach is to avoid anonymous functions so in your Product component

const Product = ({ handleAddProduct, product }) => {

  const onAddProduct = (product) => {
    handleAddProduct(product)
  }
  return (
  ...
  <Button onClick={onAddProduct}>Add to Cart</Button>
  )
)}
  • Related