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
- Open Source
- 100K+ Star di github
- Maintainer nya masih aktif
- banyak fitur tambahan dibanding menggunakan
fetchsaja
Konsep
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',
},
})
```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 status401maka 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
- digunakan didalam useEffect
useEffect(() => {
// test axios GET api
axios.get("https://reqres.in/api/users").then((response) => {
console.log(response.data);
});
}, [])
- 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)
})
},
})