-1

Im having a little trouble passing data to a map function and im not sure where im going wrong.

Im getting all the users when the component mounts, but after i get the users im trying to add a const. This all works, but then in the constructor when im trying to map the array it doesnt seem to pick it up.

class UserManagement extends Component {

    fetchUsers() {
        axios.get('http://apiyall.com/users')
            .then(res => {
                const dataTable = res.data;
            })
            .catch(err => console.log(err));
    }

    componentDidMount() {
        this.fetchUsers();
    }

    constructor(props) {
        super(props);
        this.state = {
            data: dataTable.map((prop, key) => {
CodeSauce
  • 255
  • 3
  • 19
  • 39

3 Answers3

1

Constructor is executed only once before the componentDidMount in the component life cycle. In the constructor, you can initialize the state and bind the functions. And if you want to iterate the array with 'map' function, you should receive data from props.

You should change the code as follows:

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

componentDidMount() {
    this.fetchUsers();
}

fetchUsers() {
    axios.get('http://apiyall.com/users')
    .then(res => {
        this.setState({data: res.data})  //set the state here.
    })
    .catch(err => console.log(err));
}

render() {
    this.state.data.map(() => {...});
}
freedev111
  • 132
  • 4
0

Constructor is called before ComponentDidMount. So, u cannot expect the value of datatable in constructor as it is set after that.

You can set the state in componentdidmount by using this.setState and just initialise the state in constructor.

Raghvender Kataria
  • 1,457
  • 7
  • 14
0

constructor executes only once in a component life cycle, at the time of component mounts. After that you need to make use of setState to change the state.

In the constructor you can only initialized the state like,

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

In your fetchUsers function you need to actually set the state,

fetchUsers() {
    axios.get('http://apiyall.com/users')
    .then(res => {
        this.setState({data: res.data})  //set the state here.
    })
    .catch(err => console.log(err));
}
ravibagul91
  • 20,072
  • 5
  • 36
  • 59