Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Too much recursion when updating state in react

In this example, when I try to update the state during the componentDidUpdate life cycle callback, I get a too much recursion error. How should I be updating the state?

import React from 'react';

class NotesContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { listOfShoppingItems: [] };
  }

  componentDidUpdate(nextProps, nextState) {
    let newShoppingItems = this.calculateShoppingItems();
    this.setState({ listOfShoppingItems: newShoppingItems });
  }

  calculateShoppingItems() {
    let shoppingItemsCart = []

    if (this.props.milk < 3) {
      let value = "Buy some milk";
      shoppingItemsCart.push(value);
    }

    if (this.props.bread < 2) {
      let value = "Buy some bread";
      shoppingItemsCart.push(value);
    }

    if (this.props.fruit < 10) {
      let value = "Buy some fruit";
      shoppingItemsCart.push(value);
    }

    if (this.props.juice < 2) {
      let value = "Buy some juice";
      shoppingItemsCart.push(value);
    }

    if (this.props.sweets < 5) {
      let value = "Buy some sweets";
      shoppingItemsCart.push(value);
    }

    return shoppingItemsCart;
  }

  render() {
    return (
      <div>
        Etc...
      </div>
    );
  }
}

export default NotesContainer;
like image 274
Simpleton Avatar asked Aug 25 '15 07:08

Simpleton


1 Answers

componentDidUpdate is triggered when either the props or the state has changed. If you change the state in this method, you are causing an infinite loop (unless you implement shouldComponentUpdate).

It looks like your state changes when you receive new props, therefore componentWillReceiveProps seems a good place. From the docs:

Invoked when a component is receiving new props. This method is not called for the initial render.

Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.

like image 190
gcedo Avatar answered Sep 25 '22 04:09

gcedo