Goal:
Use axios instead of fetch in order to display the data in the table
Problem:
Somehow it doesn't work when I use axios in relation to 'isLoaded'
What part of the code am I missing?
Stackblitz:
https://stackblitz.com/edit/react-cntoqk?
Info:
Newbie in 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>
</>
);
}
}
}
As Floyd already pointed out, your code should look like this
axios
.get('https://jsonplaceholder.typicode.com/comments?postId=1')
.then(response =>
this.setState({
isLoaded: true,
listData: response.data
})
);