Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 8, 2021 04:23 am GMT

Axios: My experience with the library.

image
Hey everyone and today I'm going to talk about my experience with the library axios, that makes the life off all developers, easier.

But wait, what is 'axios'??? Well from what I know and see others say axios is a promise based HTTP library, that makes api calls, like fetch, and gives you the response data direct, without all those .then(), basically it does that. Now I'm gonna show some ways I learned to use it.

First way I learned to use it

From the start the way you fetch data is simpler and direct, like the code below:

import axios from 'axios'function Foo() {  useEffect(() => {    async function handleAPI() {      const response = await axios.get('URL-YOU-WANT-TO-GET-DATA')// From this variable you can store it on some state // and you're good to go    }  })

This is some way you can use it, but there is some better ways to do it

image

Second approach, and the way I use

After using this library some times I started to see others use it and from what I could see, and the way it better fits me, is creating a folder and using it's create method, like below:

import axios from 'axios'const api = axios.create({// This baseURL is the domain URL from the api  baseURL: 'THE-DOMAIN-URL-FROM-THE-API',})export default api

And that's it you can import the file api from where you need, and just pass like this:

async function handleApiCall() {  const response = await api.get('Here you can pass the route you want')  setSomeStateHere(response.data)}

And from here I say goodbye to you all
image
I'm gonna leave the link below for the docs of the axios and you can feel free to see my github, you can see some projects that use axios!
Github Profile
Axios Docs


Original Link: https://dev.to/gabrlcj/axios-my-experience-with-the-library-2a7h

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To