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

fetch('http://example.com/movies.json')
  .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 = `https://api.github.com/users/${username}`;
  fetch(url)
    .then((res)=> res.json())
    .then((profile) => {
    const profileHtml = `
        <p><strong>${profile.name}</strong></p>
        <img src="${profile.avatar_url}" />
      `;
      document.querySelector('#github-profile').innerHTML = profileHtml;
    });

fetchGitHubProfileJSON();
Enter fullscreen mode Exit fullscreen mode

cheatsheet for fetch

Axios

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

 const fetchPokemonJSON =()=> {
  const pokemonId = 1;
  const url = `https://pokeapi.co/api/v2/pokemon/${pokemonId}`;
  axios.get(url)
    .then(res => res.data)
    .then(pokemon => {
      console.log('data decoded from JSON:', pokemon);
      const pokemonHtml = `
        <p><strong>${pokemon.name}</strong></p>
        <img src="${pokemon.sprites.front_shiny}" />
      `;
      document.querySelector('#pokemon').innerHTML = pokemonHtml;
    });
}

fetchPokemonJSON();
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

Discussion (0)