slices.mjs
1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const loginPrepareHeaders = (headers, context) => {
const { getState } = context
const state = getState()
const { data: { access_token } = {} } = loginApiSlice.endpoints.getToken.select()(state)
if (access_token) {
headers.set('authorization', `Bearer ${access_token}`)
}
return headers
}
export const loginApiSlice = createApi({
reducerPath: 'login',
tagTypes: ['Token'],
keepUnusedDataFor: 60,
baseQuery: fetchBaseQuery({
baseUrl: '/login',
}),
refetchOnReconnect: true,
endpoints: builder => ({
getToken: builder.query({
query: () => ({
url: '/token?refresh',
method: 'GET',
}),
providesTags(result, error, arg) {
const { expires_at, access_token } = result
return ['Token']
},
}),
}),
})
export const { useGetTokenQuery } = loginApiSlice
export const invalidateToken = (dispatch) => dispatch(loginApiSlice.util.invalidateTags(['Token']))