Created
October 27, 2019 18:38
-
-
Save guillaumebdx/be0b9f6372b688a523b772e8bf83a0b1 to your computer and use it in GitHub Desktop.
fetch vs axios
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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