Fetch API call in React js code example

Example 1: await fetch in react

async function fetchFunction() {
  try{
	const response = await fetch(`http://url.com`);
	const json = await response.json();
  }
  catch(err) {
    throw err;
    console.log(err);
  }
}

Example 2: React get method

/* React get method.  */

componentWillMount(){
    fetch('/getcurrencylist',
    {
        /*
        headers: {
          'Content-Type': 'application/json',
          'Accept':'application/json'
        },
        */
        method: "get",
        dataType: 'json',
    })
    .then((res) => res.json())
    .then((data) => {
      var currencyList = [];
      for(var i=0; i< data.length; i++){
        var currency = data[i];
        currencyList.push(currency);
      }
      console.log(currencyList);
      this.setState({currencyList})
      console.log(this.state.currencyList);
    })
    .catch(err => console.log(err))
  }

Example 3: how can we fetch data from api in using axios react

const users = data.map(u =>
                    <div>
                    <p>{u.id}</p>
                    <p>{u.name}</p>
                    <p>{u.email}</p>
                    <p>{u.website}</p>
                    <p>{u.company.name}

                    </div>
                    )
this.setState({users})


import React, {Component} from 'react'
import axios from '../../axios'

export default class users extends Component {
    constructor(props) {
        super(props);
        this.state = {
            Users: []
        };
    }
    getUsersData() {
        axios
            .get(`/users`, {})
            .then(res => {
                const data = res.data
                console.log(data)
                const users = data.map(u =>
                    <div>
                    <p>{u.id}</p>
                    <p>{u.name}</p>
                    <p>{u.email}</p>
                    <p>{u.website}</p>
                    <p>{u.company.name}</p>
                    </div>
                    )

                    this.setState({
                        users
                    })

            })
            .catch((error) => {
                console.log(error)
            })

    }
    componentDidMount(){
        this.getUsersData()
    }
    render() {

        return (
            <div>
                {this.state.users}
            </div>
        )
    }
}

Tags:

Misc Example