0

Is there a better way to do the following. consider this code:

this.state = {
      dates: [
        {date: '1st', matches:[]},
        {date: '2nd', matches:[]},
        {date: '3rd', matches:[]},
        {date: '4th', matches:[]},
        {date: '5th', matches:[]}
      ]
    }

  addToDates = () => {
    let dates = this.state.dates;
    const matches = this.props.matches;
    matches.forEach(function(match){
      dates.forEach(function(date){
        if (match.date == date.date){
          this.setState({dates: this.state.dates.concat(match)})
        }
      })
    })
  }

what i am trying to do is iterate through 2 arrays and if i find a match that has the same date as a date then i want to add it to the matches array.

2 problems, firstly is there a better way to compare 2 arrays rather than iterating through both? secondly i get cant read setState of undefined even though i have:

this.addToDates = this.addToDates.bind(this) bound it in my constructor. i thought arrow functions solved that scoping too?
The Walrus
  • 1,148
  • 6
  • 28
  • 46

1 Answers1

0

You need to use arrow functions in your addToDate method. You don't actually have to bind addToDates in your constructor as you are using an arrow function as a class property.

The value of this when you are using this.setState is different if you don't use an arrow functions for your forEach loops.

addToDates = () => {
  let dates = this.state.dates;
  const matches = this.props.matches;
  matches.forEach(match =>{
    dates.forEach(date =>{
      if (match.date == date.date){
        this.setState({dates: this.state.dates.concat(match)})
      }
    });
 });

As per MDN

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming. An arrow function does not create its own this, the this value of the enclosing execution context is used.

Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54