DEV Community

Cover image for TIL - Ajax (Asynchronous requests) with Fetch and Axios + React
Anne Quinkenstein
Anne Quinkenstein

Posted on • Updated on

TIL - Ajax (Asynchronous requests) with Fetch and Axios + React

Instead of retrieving a whole webpage once, ajax allows us to retrieve individual data items from the server to update sections of a webpage without having to load an entire new page.
This led to the creation of technologies that allow web pages to request small chunks of data using APIs like XMLHttpRequest or — nowadays — the Fetch API.

Fetch does not retrieve the data immediately. It takes some time for the request to reach the server, and for it to respond with the requested data. Therefore, a mechanism exists to indicate that you want to execute code only after you have obtained the answer to the request.

A basic fetch request

  .then(response => response.json())
  .then(data => console.log(data));
Enter fullscreen mode Exit fullscreen mode
  1. calculate the url to be queried, which we then switch to fetch
  2. wait for data response (async) & then resolve it as json
  3. then take data & do something with the data obtained
const fetchGitHubProfileJSON = () => {
  const username = 'AnneQuinkenstein';
  const url = `${username}`;
    .then((res)=> res.json())
    .then((profile) => {
    const profileHtml = `
        <img src="${profile.avatar_url}" />
      document.querySelector('#github-profile').innerHTML = profileHtml;

Enter fullscreen mode Exit fullscreen mode

cheatsheet for fetch


Advantages comparing to fetch: the automatic transformation of JavaScript objects into JSON and vice versa & better error management mechanisms
$ yarn add axios

 const fetchPokemonJSON =()=> {
  const pokemonId = 1;
  const url = `${pokemonId}`;
    .then(res =>
    .then(pokemon => {
      console.log('data decoded from JSON:', pokemon);
      const pokemonHtml = `
        <img src="${pokemon.sprites.front_shiny}" />
      document.querySelector('#pokemon').innerHTML = pokemonHtml;

Enter fullscreen mode Exit fullscreen mode

GitHub for first Example

API with React

Get Data from the API & store it in App's state.
The "parent" component will make the API calls, and pass the received information to the "child" component(s).
axios with React

Top comments (0)