Skip to content

Instantly share code, notes, and snippets.

@LeroViten
Last active October 13, 2022 20:48
Show Gist options
  • Save LeroViten/150d7423de4259bd2fdd27f9fb17e7c3 to your computer and use it in GitHub Desktop.
Save LeroViten/150d7423de4259bd2fdd27f9fb17e7c3 to your computer and use it in GitHub Desktop.
RTK-query-auth-attempt
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const authApi = createApi({
reducerPath: 'authApi',
baseQuery: fetchBaseQuery({
baseUrl: 'https://my-api.herokuapp.com/',
prepareHeaders: (headers, { getState }) => {
const token = getState().authApi.data.token;
// If we have a token in localStorage, lets use it:
if (token) {
headers.set('Authorization', `Bearer ${token}`);
}
return headers;
},
}),
endpoints: builder => ({
fetchUser: builder.query({
query: () => `/users/current`,
}),
createUser: builder.mutation({
query: ({ name, email, password }) => ({
url: '/users/signup',
method: 'POST',
body: {
name,
email,
password,
},
}),
}),
loginUser: builder.mutation({
query: ({ email, password }) => ({
url: '/users/login',
method: 'POST',
body: {
email,
password,
},
}),
}),
logoutUser: builder.mutation({
query: () => ({
url: '/users/logout',
method: 'POST',
}),
}),
}),
});
export const {
useFetchUserQuery,
useCreateUserMutation,
useLoginUserMutation,
useLogoutUserMutation,
} = authApi;
async function handleSubmit(e) {
const email = e.currentTarget.email.value;
const password = e.currentTarget.password.value;
e.preventDefault();
const loginData = {
email,
password,
};
if (email && password) {
loginUser(loginData);
// looks like here I need to unwrap().then(credentials)
toast.success('You logged in! 🚀');
history.push('/');
} catch (err) {
toast.error(err.message);
}
}
@kayprogrammer
Copy link

How do you then handle refresh token

@LeroViten
Copy link
Author

LeroViten commented Aug 24, 2022

in services folder there's axiosBaseQuery.js script that does everything:

Look here

@kayprogrammer
Copy link

Thank you very much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment