Last active
October 13, 2022 20:48
-
-
Save LeroViten/150d7423de4259bd2fdd27f9fb17e7c3 to your computer and use it in GitHub Desktop.
RTK-query-auth-attempt
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
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; |
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
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); | |
} | |
} |
in services folder there's axiosBaseQuery.js script that does everything:
Thank you very much
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do you then handle refresh token