Maximilian Witte
Maximilian Witte

Reputation: 11

This.state is 0 inside .map

Iam trying to convert all selected item id's from a redux store into the item names and save it into state.

My problem is that the spread operator inside the setState function is equal to zero. Do I have to bind the context of the function to the class?

  constructor(props) {
    super(props);
    this.state = {
      item_Name: []
    };
}




  componentDidMount() {
    this.props.Cart_Items.Id.map((item, i) => {
      if (item === "001") {
        // The problem is that this.state.item_Name is 0
        console.log(this.state.item_Name)
        this.setState({
          item_Name: [...this.state.item_Name, "Buddha"]
        });
      }
    })
  }

Thanks for your help!

Upvotes: 1

Views: 49

Answers (1)

Sagiv b.g
Sagiv b.g

Reputation: 31024

setState is asynchronous and will batch updates.
Another thing, .map is returning an array, so just store the new array in a variable and pass it to setState.

P.S, you are checking for a condition inside .map. but .map should return the same number of members, add an else or just use .filter or .reduce.

  componentDidMount() {
    const nextState = this.props.Cart_Items.Id.map((item, i) => {
      if (item === "001") {
        return "Buddha"
      }
      // you need an else here because map should return the same number of members, or use .filter or .reduce
    })
    this.setState({item_name: nextstate});
  }

Upvotes: 1

Related Questions