Skip to content

Instantly share code, notes, and snippets.

@akursat
Created September 20, 2021 07:41
Show Gist options
  • Select an option

  • Save akursat/c4ed706204c3b0b93ba358039eee9296 to your computer and use it in GitHub Desktop.

Select an option

Save akursat/c4ed706204c3b0b93ba358039eee9296 to your computer and use it in GitHub Desktop.

Revisions

  1. akursat created this gist Sep 20, 2021.
    28 changes: 28 additions & 0 deletions auth.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    /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