Created
September 20, 2021 07:41
-
-
Save akursat/c4ed706204c3b0b93ba358039eee9296 to your computer and use it in GitHub Desktop.
Rtk query authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/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