Hi!
I have a Django + DRF backend and I'm trying to implement a frontend (this is my first project). I have a login form and when you submit the form, I want to send a request to the backend that fetches the user object.
here's the current implementation of my Login component:
{/* imports */}
const Login = () => {
const {
register,
handleSubmit,
formState: { errors },
setError,
} = useForm<FormData>();
const router = useRouter();
const { login, storeToken, getToken } = AuthActions();
const { user, isError, isLoading, isValidating } = useUserData();
const accessToken = getToken('accessToken');
const onSubmit = async (data: FormData) => {
await login(data.email, data.password)
.json((json) => {
storeToken(json.access, 'access');
storeToken(json.refresh, 'refresh');
})
.catch((err) => {
setError('root', { type: 'manual', message: err.json.detail });
});
{/* redirect user based on user.role */}
// would be nice to show a spinner while it's validating or loading,
// but this won't work since we're running this in the onSubmit function I guess?
if (isLoading || isValidating || !accessToken) {
return <Spinner />;
}
if (isError) {
return <div>Error fetching user data</div>;
}
};
return (
{*/ return the Login component */}
};
export default Login;
what I need: the login() method saves the jwt token into a cookie. the useUserData() is a hook, that fetches the user object from the backend via SWR, but it needs the JWT token first. right now if I submit the form, and there's no token created yet (eg. first user), my login flow will break.
I admit, I'm new to frontend, I'm struggling with the concepts, please let me know how should I approach this problem.