kirdua
kirdua

Reputation: 95

Reactjs setState not working

I'm running into an issue where my console is telling me setState is not defind. I'm not sure what I'm doing wrong. I preload the my object (data) in the constructor. I then pass it through to a table where it is displayed. When a user then selects an option from a dropdown it should only show the filtered data. I've bound the function in the constructor so I'm not sure what I've done wrong. Code is below:

import React, {Component} from ‘react’;
import moment from ‘moment’;
import {Table} from ‘reactstrap’;
import classnames from ‘classnames’;

class Tasks extends Component {


  constructor(props){

    super(props);

    this.state = {

         data: [
        {
          “task_number”:””,
          “work_end”:”10/01/2017”
        },
        {
        etc…
        }
         ]

    }

    this.checkDate = this.checkDate.bind(this);
  }


   checkDate(e) {
    let d = moment.format(“MM/DD/YYYY”);
    let currentData = this.state.data;

    currentData.filter(function(newData){
       if(newData.work_end < d){

         //comes back as undefined
         this.setState({data: newData});
       }
    });
   }

  render(){
    const { data } = this.state;


    let myData = data.map((header, i){
    return (<tr key = {i}>
          <td>{data[i].task_number}</td>
         <td>{data[i].work_end}</td>
                     </tr>)
    });

    return(
        <div>
            <table>
                {myData}
            </table>

        <Input type=“select”
                           name=“assigngroup”
             id=“assigngroup”
            value={this.state.value}
            onChange={this.checkDate}
            />
        </div>
    );
  }


}

export default Tasks;

I've also tried creating a new function and passing it from checkDate, but that failed as well.

Upvotes: 0

Views: 5160

Answers (2)

Steve Holgado
Steve Holgado

Reputation: 12089

The filter method returns a new filtered array.

Try this:

checkDate(e) {
  let d = moment().format(“MM/DD/YYYY”)
  let currentData = this.state.data
  let filteredData = currentData.filter(item => item.work_end < d)

  this.setState({ data: filteredData })
}

Upvotes: 1

Jalissa
Jalissa

Reputation: 876

In Javascript, functions have their own scope so in checkDate this is your component but, inside the function that you use to filter your currentData, this is something else.

Your code should go like this:

currentData.filter(newData => {
   if(newData.work_end < d){

     this.setState({data: newData});
   }
});

or just save this in a variable:

var self = this;

currentData.filter(function(newData){
   if(newData.work_end < d){

     self.setState({data: newData});
   }
});

Upvotes: 2

Related Questions