0

This is my code for component employ which not set data but gets count rows correct ( empty ).

I want to set the data after fetching from the server-side.

import React, { Component } from 'react';

export class Employ extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            employ: []
        };
    }

    componentDidMount() {
        fetch("api/SampleData/GetEmpl")

            .then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        employ: result
                    });
                }
            );
    }

    render() {
        return (
            <div>
                <h2>Employ Data...</h2>
                <table className="table stripted bordered hover">
                    <thead>
                        <tr>
                            <th>EmployeeID</th>
                            <th>FullName</th>
                            <th>EMPCode</th>
                            <th>Mobile</th>
                            <th>Position</th>
                        </tr>
                    </thead>
                    <tbody>
                        {this.state.employ.map(emp => (
                            <tr key={Math.random()}>
                                <td>{emp.EmployeeID}</td>
                                <td>{emp.FullName}</td>
                                <td>{emp.EMPCode}</td>
                                <td>{emp.Mobile}</td>
                                <td>{emp.Position}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        );
    }

}

I used Asp.net.Api.core for connecting database(backend).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    Sidenote: When mapping over the employ inside JSX, do not use `key={Math.random()}` as react wont be able to keep track of items on rerenders. Instead you could use `key={emp.EmployeeID}` as long as its a unique value. – Ishant Solanki Jun 01 '20 at 08:43

1 Answers1

0

You can use setState as callback function.

import React, { Component } from 'react';

export class Employ extends Component {
    constructor(props) {
        super(props);
        this.state = {
            employ: []
        };
    }

    componentDidMount() {
        fetch("api/SampleData/GetEmpl")
            .then(res => res.json())
                .then(result => {
                    this.setState(() => ({
                        employ: result
                    }))
                })
    }

    render() {
        return (
            <div>
                ... YOUR JSX CODE GOES HERE ...
            </div>
        )
    }
}
Fatema Tuz Zuhora
  • 3,088
  • 1
  • 21
  • 33