Skip to main content

Menggunakan Axios untuk Mengambil Data

Axios merupakan HTTP Client library untuk nodejs dan browser. pengenalan menganai axios lebih lanjut bisa baca artikel ini Intro Axios

axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});

Pros Axios​

  1. Open Source
  2. 100K+ Star di github
  3. Maintainer nya masih aktif
  4. banyak fitur tambahan dibanding menggunakan fetch saja

Konsep​

  1. Axios Instance dapat digunakan untuk custom config http request secara global contohnya ingin mengganti headers nya agar semua http request yang dilakukan dengan axios bertipe application/json, bisa juga untuk mendeclare baseUrl nya sehingga ketika melakukan http request tidak perlu menuliskan kembali baseUrl nya langsung path nya saja'

    ```tsx
    const axiosInstance = axios.create({
    baseURL: import.meta.env.VITE_API_BASEURL,
    headers: {
    'Content-Type': 'application/json',
    },
    })
    ```
  2. Interceptor digunakan untuk mencegat request dan atau response sebelum http request tersebut di handle oleh then / catch. bisa dimanfaatkan untuk kebutuhan autentikasi contohnya ketika http request memberikan respon status 401 maka lempar user ke halaman login.

    ```tsx
    // Add a request interceptor
    axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
    }, function (error) {
    // Do something with request error
    return Promise.reject(error);
    });

    // Add a response interceptor
    axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
    }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
    });
    ```

Contoh​

  1. digunakan didalam useEffect
useEffect(() => {
// test axios GET api
axios.get("https://reqres.in/api/users").then((response) => {
console.log(response.data);
});
}, [])
  1. digunbakan bersama dengan ReactQuery
const { data } = useQuery({
queryKey: ['users'],
queryFn: async () => {
return axios
.get("https://reqres.in/api/users")
.then((res) => {
console.log(res.data)
})
},
})