Skip to content

Instantly share code, notes, and snippets.

@guillaumebdx
Created October 27, 2019 18:38
Show Gist options
  • Save guillaumebdx/be0b9f6372b688a523b772e8bf83a0b1 to your computer and use it in GitHub Desktop.
Save guillaumebdx/be0b9f6372b688a523b772e8bf83a0b1 to your computer and use it in GitHub Desktop.
fetch vs axios
import React, {Component} from 'react';
import axios from "axios";
class Table extends Component
{
constructor()
{
super()
this.state = {
titles: [],
}
this.postApi = this.postApi.bind(this);
this.postApiFetch = this.postApiFetch.bind(this);
}
componentDidMount()
{
axios.get("http://localhost:8000/item/all")
.then(response => response.data)
.then(data => this.setState({titles : data}))
}
postApi() {
axios.post('http://localhost:8000/item/add',JSON.stringify({title: 'Cyril Hanou'}))
.then(function(response){
console.log(response);
}).catch(function (error) {
console.log(error);
});
}
postApiFetch()
{
let apiData = {
title : 'cyril2'
}
fetch('http://localhost:8000/item/add', {
method: 'POST',
body: JSON.stringify(apiData)
});
}
render()
{
const Thead = () => {
return(
<thead>
<tr>
<td>
id
</td>
<td>
Title
</td>
</tr>
</thead>
)
}
const {titles} = this.state;
const Tbody = () => {
return (
<tbody>
{titles.map(row =>
<Row
name = {row.id}
job = {row.title}
key = {row.id}
/>
)}
</tbody>
)
}
const Row = (props) => {
return (
<tr>
<td>{props.name}</td>
<td>{props.job}</td>
</tr>
)
}
return(
<div>
<button type="button" onClick={this.postApi}>Click api axios</button>
<button type="button" onClick={this.postApiFetch}>Click api fetch</button>
<table className={this.props.size}>
<Thead />
<Tbody />
</table>
</div>
)
}
}
export default Table;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment