How to use Axios for API call and error handling in React

 Index.js

-------------


const axios = require('axios');

const fake = document.getElementById('fake');

// GET REQUEST
const getFakeData = () => {
  axios
    .get('https://jsonplaceholder.typicode.com/posts')
    .then(res => {
      console.log('res'res.data);
      handleAPI(res.data);
      return res;
    })
    .catch(error => {
      console.log('err1 'error);
      errorHandle(error);
      return error;
    });
};

// getFakeData();

// POST REQUEST

const postFakeData = () => {
  axios
    .post('https://jsonplaceholder.typicode.com/posts', {
      body: JSON.stringify({
        title: 'football',
        body: 'bar1',
        userId: 2
      })
    })
    .then(response => {
      console.log(response.data);
      console.log(response);
      return response;
    })
    .catch(error => {
      console.log('err1 'error);
      errorHandle(error);
      return error;
    });
};

postFakeData();

function handleAPI(res) {
  res.map((eachindex=> {
    let singleEle = each.title;
    fake.innerHTML += `<article>${index + 1} ${singleEle} </article>`;
  });
}

function errorHandle(err) {
  fake.innerHTML = `<h4> ${err.message}</h4>
  <br>
  <article> ${err.stack}</article>`;
}

index.html :
----------------

<div id="app"></div>



<div id="fake"></div>

0 Comments