Cannot read properties of undefined (reading 'setState'), Laravel-React , I'm new fresher for laravel-react

Viewed 37

enter image description here

enter code here

class Table extends Component {

constructor(props) {
    super(props);
    
    this.state = {
        employee: [],
    }
}
//Life Sycle Methord
componentDidMount() {
    this.getEmployeeList();
}

// Get Employee List
getEmployeeList = (e) => {
    axios.get('get/employee/list').then(function (response) {
        console.log(response.data);
        this.setState({
            employee : response.data,
        });
         
    })
}

render() {
    return (
        <div className="container">
            <div className="row justify-content-center">
                <div className="col-md-8">
                    <div className="card">
                        <table className="table table-hover">
                            <thead>
                                <tr>
                                    <th scope="col" width="100px">#</th>
                                    <th scope="col" width="100px">Name</th>
                                    <th scope="col" width="100px">Slary</th>
                                    <th scope="col" width="100px">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                {this.state.employee.map(function (x, i) {
                                    <TableRow key={i} data={x} />
                                })}

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    );
}

}

export default Table;

When I try this code(as above mentioned image https://i.stack.imgur.com/gazFY.png), I'm getting an error as below...

"Cannot read properties of undefined (reading 'setState')"

1 Answers

you can directly call this.setState in the getEmployeeList..


constructor(props) {
    super(props);
    
    this.state = {
        employee: [],
    }
    this.getEmployeeList = this.getEmployeeList.bind(this);
}
async functiion getEmployeeList(e) {
    const response = await axios.get('get/employee/list');
        console.log(response.data);
        this.setState({
            employee : response.data,
        });
}

Is there any particular reason, that you are assigning this to the variable self. also this keyword works differently in the normal function & in the arrow function..

Refer..

How does the "this" keyword work, and when should it be used?

Related