DEV Community

Cover image for What I learned while studying Data fetching with Axios
Matheus 🇧🇷
Matheus 🇧🇷

Posted on

What I learned while studying Data fetching with Axios

Hello everyone!

I’m back, and now I learned one more thing. I learned how to make requests. I’m here to show how I did that, and which concepts I learned to do it.

https://i.imgur.com/UBBab71.png

Using TV API | TVmaze

WEB APIs

The interfaces are HTTP-based, where we consume data through endpoints.

https://i.imgur.com/fyopIdJ.png

HTTP-based also means that we can communicate with these endpoints through HTTP verbs. This means, the different types of requests we can send (get, post, delete.. )

  • GET: To get or retrieve an information
  • POST: To send data to be stored in a database.
  • DELETE: To delete something via API

There are others.

PROMISES

An object that represents the success or failure of an asynchronous operation. It was great to learn about. Because with promises we can avoid the callback hell.

Promises can have three states:

  • Pending: In the beginning, it is waiting to be fulfilled or rejected.
  • Fulfilled: Operation was successful
  • Rejected: Operation failed.

https://i.imgur.com/ZjRwasz.png

The great thing about Promises is these two important methods that we can attach to the objects to call our callbacks (then and catch).

FETCH API

The Fetch allows to make requests using function and supports promises. Since it supports promises we can use the powerful methods that I said before.

AXIOS

It’s a great library for making HTTP requests, instead of calling fetch(url), we call axios.get(url).

And why bother?

Because with Axios, I don’t need to parse the data.

https://i.imgur.com/9ls2kuU.png

ASYNC

I’m not going deep here, but here is fascinating because async functions always return a promise. With async/await, it waits for the promises to be fulfilled, so when it’s successful executes the next instruction.

Let’s start it!

In the Axios’s docs (https://axios-http.com/docs/intro), you can get the CDN, so I don’t need to install it.

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

A. Creating the HTML body

<body>
    <h1>TV Search</h1>
    <form id="form">
        <input id="userInput" name="userInput" type="text">
        <button id="submit">Submit</button>
    </form>

    <div class="shows"></div>

    <script src="main.js"></script>
</body>
Enter fullscreen mode Exit fullscreen mode

B. I only need this to my CSS

.shows {
  display: flex;
  flex-wrap: wrap;
}

div {
  margin: 10px;
}
Enter fullscreen mode Exit fullscreen mode

C. Creating the addEventListener to every interaction with the submit button.

const form = document.querySelector('#form');
const showsContainer = document.querySelector('.shows');

form.addEventListener('click', (e) => {
  e.preventDefault();
  console.log('btn pressed');
});
Enter fullscreen mode Exit fullscreen mode

Here, it’ll prevent that every time we submit (make a request), the page doesn’t reload.

Inside this addEventListener, I want to make a request to the WEB API, to get the TV Shows with the name I’m looking for.

Looking at the documentation from TVMaze (https://www.tvmaze.com/api), the Show Search endpoint works with a query.

Using template literals (backticks), I can capture each input from the user and modify it directly in the query.

const form = document.querySelector('#form');
const showsContainer = document.querySelector('.shows');

form.addEventListener('click', async (e) => {
  e.preventDefault();
  const userInput = document.querySelector('#userInput').value;
  const URL = `https://api.tvmaze.com/search/shows?q=${userInput}`;

  //make the request
  const res = await axios.get(URL);
  console.log(res.data);
});
Enter fullscreen mode Exit fullscreen mode

D. DOM manipulation

With everything I’ve studied before for DOM Manipulation, I can work with this data, to generate images and a title, for each show found.

const form = document.querySelector('#form');
const showsContainer = document.querySelector('.shows');

form.addEventListener('click', async (e) => {
  e.preventDefault();
  const userInput = document.querySelector('#userInput').value;
  const URL = `https://api.tvmaze.com/search/shows?q=${userInput}`;

  //make the request
  const res = await axios.get(URL);
  console.log(res.data);

  const img = document.createElement('img');
  const title = document.createElement('h1');
  img.src = res.data[0].show.image.medium;
  title.textContent = res.data[0].show.name;
  document.body.append(title);
  document.body.append(img);
});
Enter fullscreen mode Exit fullscreen mode

For the first show in the data’s Array, it will create an h1 and an image for it.

https://i.imgur.com/eMYbfpg.png

E. Create new functions to evaluate more shows, not only the first one.

E.1 Here, I want to create a limit, a maximum of five shows to be show in the page.

const limitShows = (data) => {
  let numberOfShows = [];
  if (data.length >= 5) {
    for (let i = 0; i < 5; i++) {
      numberOfShows.push(data[i]);
    }
  } else {
    for (let show of data) {
      numberOfShows.push(show);
    }
  }

  return numberOfShows;
};
Enter fullscreen mode Exit fullscreen mode

E.2 Here, I’m going to create another function to print the title and image for each show collected in the previous array.

const publishShows = (shows) => {
  shows.forEach((show) => {
    const img = document.createElement('img');
    const title = document.createElement('h1');
    const div = document.createElement('div');
    img.src = show.show.image.medium;
    title.textContent = show.show.name;

    div.appendChild(title);
    div.appendChild(img);
    showsContainer.appendChild(div);
  });
};
Enter fullscreen mode Exit fullscreen mode

F. Cleaning my addEventListener and calling the functions

form.addEventListener('click', async (e) => {
  e.preventDefault();
  const userInput = document.querySelector('#userInput').value;
  const URL = `https://api.tvmaze.com/search/shows?q=${userInput}`;

  //make the request
  const res = await axios.get(URL);
  const shows = limitShows(res.data);
  publishShows(shows);
});
Enter fullscreen mode Exit fullscreen mode

Is it done?

Yes and No!

There is a lot of room for improvement here.

Known Issues:

  • If a new request is made, the page is not cleared;
  • There is nothing to handle errors. What will happen if the promise is rejected?

There are many new concepts here, that I learned to put this project working, if you want to take a look, here is the repo.

I'm sharing my journey of learning web development on Twitter, follow me.

See you next time!

Top comments (0)