Progress Bar: Axios Interceptors
it’s important to design user-friendly applications that give feedback when parts of your webpage are still loading.
웹페이지의 일부가 여전히 로드 중일 때 피드백을 제공하는 사용자 친화적인 애플리케이션을 디자인하는 것이 중요합니다.
- Installing NProgress
- Using Axios Interceptors
Problem: Our API calls might not always be super fast
let our users know the data is on the way, and have something happen when they click a link that requires an API call.
사용자에게 데이터가 전송 중임을 알리고 API 호출이 필요한 링크를 클릭하면 어떤 일이 발생하도록 합니다.
Solution #1: Progress Bar using API Interceptors
$ npm install nprogress
/src/main.js
include the CSS for it inside our main.js
...
import store from './store/store'
import BaseIcon from '@/components/BaseIcon'
import 'nprogress/nprogress.css' // <-----
Using Axios Interceptors
Axios Interceptors allow us to intercept our requests and responses adding additional functionality, like starting and stopping a progress bar.
Axios 인터셉터를 사용하면 progress bar 시작 및 중지와 같은 추가 기능을 추가하여 요청 및 응답을 가로챌 수 있습니다.
Axios Interceptors can be useful for many things including:
Axios Interceptors는 다음을 포함한 다양한 용도에 유용할 수 있습니다.
- On request to set proper authorization tokens.
- 적절한 인증 토큰을 설정하라는 요청 시.
- On response to format or filter data before it reaches into your app.
- 데이터가 앱에 도달하기 전에 데이터 형식을 지정하거나 필터링하는 것에 대한 응답입니다.
- On response to catch 401 not authorized responses.
- 응답 시 승인되지 않은 401을 잡기 위한 응답입니다.
/src/services/EventService.vue
import axios from 'axios'
const apiClient = axios.create({
baseURL: `http://localhost:3000`,
withCredentials: false, // This is the default
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
export default {
getEvents(perPage, page) {
return apiClient.get('/events?_limit=' + perPage + '&_page=' + page)
},
getEvent(id) {
return apiClient.get('/events/' + id)
},
postEvent(event) {
return apiClient.post('/events', event)
}
}
current codes changes by adding Axios Interceptors to our code.
/src/services/EventService.vue
import axios from 'axios'
import NProgress from 'nprogress' // <--- Import the library
const apiClient = axios.create({ ... })
apiClient.interceptors.request.use(config => { // Called on request
NProgress.start()
return config
})
apiClient.interceptors.response.use(response => { // Called on response
NProgress.done()
return response
})
...
With the -d 1500, the API server will add a 1.5 second (1,500 millisecond) delay before returning our data.
-d 1500을 사용하면 API 서버가 데이터를 반환하기 전에 1.5초(1,500밀리초)의 지연을 추가합니다.
$ json-server -d 1500 db.json
Caveat #1 - Not optimal for multiple API calls at the same time
This works great until we are using two or more API calls to load a page.
이는 페이지를 로드하기 위해 두 개 이상의 API 호출을 사용할 때까지 훌륭하게 작동합니다.
A common solution to this problem is to create a loading Vuex module that holds the loading State.
이 문제에 대한 일반적인 해결책은 로딩 상태를 보유하는 로딩 Vuex 모듈을 만드는 것입니다.
Caveat #2 - Templates get rendered before the API call is returned
In-Component Route Guards and then using Global with Per-Route Guards can address this issue.
In-Component Route Guards를 사용하고 Per-Route Guards와 함께 Global을 사용하면 이 문제를 해결할 수 있습니다.
Resources
Create a global loading progress indicator using Vuex, Axios, and NProgress
addressing Caveat #1 - Not optimal for multiple API calls at the same time
Create a global loading progress indicator using Vuex, Axios, and NProgress
Vue applications often need to process many API requests while a page is loading. Here is a simple way to show a progress indicator.
medium.com
Sample codes
https://github.com/Code-Pop/real-world-vue/releases/tag/progress-bar-axios-interceptors-finish
Release progress-bar-axios-interceptors-finish · Code-Pop/real-world-vue
Progress bar with axios interceptors
github.com
https://ricostacruz.com/nprogress/
NProgress: slim progress bars in JavaScript
NProgress.start() — shows the progress bar NProgress.set(0.4) — sets a percentage NProgress.inc() — increments by a little NProgress.done() — completes the progress Download v Perfect for Turbolinks, Pjax, and other Ajax-heavy apps.
ricostacruz.com
https://github.com/axios/axios
GitHub - axios/axios: Promise based HTTP client for the browser and node.js
Promise based HTTP client for the browser and node.js - GitHub - axios/axios: Promise based HTTP client for the browser and node.js
github.com
'Java Scripts > Vue.js' 카테고리의 다른 글
Vue 3 -Teleport (0) | 2022.03.22 |
---|---|
Vue : Error Handling and 404s (0) | 2022.01.16 |
Vue : API calls with Axios (0) | 2022.01.08 |
Vue : Global Component (0) | 2022.01.08 |
Vue : Single File Component (0) | 2022.01.08 |