Meta:
Use axios en lugar de fetch para mostrar los datos en la tabla
Problema:
De alguna manera no funciona cuando uso axios en relación con 'isLoaded' ¿Qué parte del código me falta?
Apilado:
https://stackblitz.com/edit/react-cntoqk ?
Información:
Novato en Reactjs
import React from 'react'; import './style.css'; import React, { Component } from 'react'; import axios from 'axios'; export default class App extends Component { constructor() { super(); this.state = { isLoaded: false, listData: {} }; } componentDidMount() { /** fetch('https://jsonplaceholder.typicode.com/comments?postId=1') .then(results => results.json()) .then(data => this.setState({ isLoaded: true, listData: data }) ) .catch(err => console.log(err)); */ axios .get('https://jsonplaceholder.typicode.com/comments?postId=1') .then(response => this.setState({ isLoaded: true, listData: data }) ); } render() { const { isLoaded } = this.state; if (!isLoaded) { return <div>Loading...</div>; } else { return ( <> <table className="table"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> {this.state.listData && this.state.listData.map(item => { return ( <tr key={item.id.toString()}> <td>{item.id}</td> <td>{item.name}</td> <td>{item.email}</td> </tr> ); })} </tbody> </table> </> ); } } }Como ya señaló Floyd, su código debería verse así
axios .get('https://jsonplaceholder.typicode.com/comments?postId=1') .then(response => this.setState({ isLoaded: true, listData: response.data }) );