Skip to content

Instantly share code, notes, and snippets.

@akursat
Created September 20, 2021 07:41
Show Gist options
  • Save akursat/c4ed706204c3b0b93ba358039eee9296 to your computer and use it in GitHub Desktop.
Save akursat/c4ed706204c3b0b93ba358039eee9296 to your computer and use it in GitHub Desktop.
Rtk query authentication
/example from https://redux-toolkit.js.org/rtk-query/usage/examples#authentication
export const api = createApi({
baseQuery: fetchBaseQuery({
baseUrl: '/',
prepareHeaders: (headers, { getState }) => {
// By default, if we have a token in the store, let's use that for authenticated requests
const token = (getState() as RootState).auth.token
if (token) {
headers.set('authorization', `Bearer ${token}`)
}
return headers
},
}),
endpoints: (builder) => ({
login: builder.mutation<UserResponse, LoginRequest>({
query: (credentials) => ({
url: 'login',
method: 'POST',
body: credentials,
}),
}),
protected: builder.mutation<{ message: string }, void>({
query: () => 'protected',
}),
}),
})
export const { useLoginMutation, useProtectedMutation } = api
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment