Skip to content

Commit 2644877

Browse files
committed
Axios interceptor
1 parent a996443 commit 2644877

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

db.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@
4949
"name": "hello",
5050
"alterEgo": "world",
5151
"id": 10
52+
},
53+
{
54+
"name": "Updated",
55+
"alterEgo": "axios interceptors",
56+
"id": 11
5257
}
5358
],
5459
"friends": [

src/api/Api.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import axios from 'axios'
2+
3+
const client = axios.create({ baseURL: 'http://localhost:4000' })
4+
5+
export const request = ({ ...options }) => {
6+
client.defaults.headers.common.Authorization = 'Bearer token'
7+
8+
const onSuccess = (response: any) => response
9+
const onError = (error: Error) => {
10+
// optionaly catch errors and add additional logging here
11+
return error
12+
}
13+
14+
return client(options).then(onSuccess).catch(onError)
15+
}

src/lib/hooks/useSuperHeroesData.tsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
import { useQuery, useMutation, useQueryClient } from 'react-query'
22
import axios from 'axios'
3-
import { SuperHero } from 'interfaces'
3+
import { request } from 'api/Api'
44

55
interface Props {
66
onSuccess: (response: any) => void
77
onError: (error: Error) => void
88
}
99

1010
const fetchSuperHeroes = () => {
11-
return axios.get('http://localhost:4000/superheroes')
11+
return request({ url: '/superheroes' })
1212
}
1313

1414
const addSuperHero = (hero: { name: string; alterEgo: string }) => {
15-
return axios.post('http://localhost:4000/superheroes', hero)
15+
return request({ url: '/superheroes', method: 'post', data: hero })
1616
}
1717

1818
export const useSuperHeroesData = ({ onSuccess, onError }: Props) => {

0 commit comments

Comments
 (0)