简体   繁体   中英

Unable to bind API data to this.setState in React JS using fetch

I'm new to React JS and I have a problem in displaying data in table through fetch API call. Am able to get JSON data but unable to bind the data to this.State object. It always throws the following error.

index.bundle.js:49 Uncaught ReferenceError: users is not defined

May I know what am doing wrong. Here is my code.

import React, {Component} from "react";
import { Badge, Row, Col, Card, CardHeader, CardBlock, Table, Pagination, PaginationItem, PaginationLink} from "reactstrap";

class Users extends Component {


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

  componentDidMount(){

     fetch('http://some_ip_address/api/subuserlist',{
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'filterfield': 'group_id',
          'filtervalue': 'random_filter_value'
        }
     }).then(result=>result.json())
       .then(function(data) {
          console.log(data);           //able to print data
          this.setState({users:data});
          console.log(users);        //unable to print users
       }.bind(this))    
       .catch(function(error) {
         // If there is any error you will catch them here
       });   
  }

  render() {
      return (
        <div className="animated fadeIn">
         <Row>
          <Col>
            <Card>
              <CardHeader>
                <i className="fa fa-align-justify"></i> Combined All Table
              </CardHeader>
              <CardBlock className="card-body">
                <table>
                  <tbody>
                   {this.state.users && this.state.users.map(function(users) {                  
                      return (
                          <tr>
                              <td>{users.firstName}</td>
                          </tr>
                        )

                    })}</tbody>
                </table>
              </CardBlock>
            </Card>
          </Col>
        </Row>
      </div>
   );
 }
}

export default Users;

You're getting this error because users isn't defined in the scope of your callback function (in Fetch). Replace console.log(users); with console.log(this.state.users); . Also, you're gonna have to change your callback from a regular anonymous function to an arrow function, otherwise this won't refer to your class, it'll refer to the callback function.

  componentDidMount(){
     fetch('http://some_ip_address/api/subuserlist',{
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'filterfield': 'group_id',
          'filtervalue': 'random_filter_value'
        }
     }).then(result=>result.json())
       .then((data) => {
          console.log(data);           //able to print data
          this.setState({
            users:data
          }, () => {
            console.log(this.state.users); // This will be fired after setState has completed.
          });
       })    
       .catch(function(error) {
         // If there is any error you will catch them here
       });   
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM