#Successful login not redirect to host page || React Router 6 / Actions and Protected Routes / useNav

3 messages · Page 1 of 1 (latest)

daring skiff
#

Currently on path React Router 6 / Actions and Protected Routes / useNavigation in VanLife.

Successful form login is supposed to redirect to ‘/host’ page instead application throwing error.

Made sure to clear localStorage as well.

Login.jsx

import 'react';
import {
  useLoaderData,
  useNavigation,
  Form,
  redirect,
  useActionData,
} from 'react-router-dom';
import { loginUser } from '../../api';

export function loader({ request }) {
  return new URL(request.url).searchParams.get('message');
}

export async function action({ request }) {
  const formData = await request.formData();
  const email = formData.get('email');
  const password = formData.get('password');
  try {
    const data = await loginUser({ email, password });
    localStorage.setItem('loggedin', true);
    return redirect('/host');
  } catch (err) {
    return err.message;
  }
}

export default function Login() {
  const errorMessage = useActionData();
  const message = useLoaderData();
  const navigation = useNavigation();

  return (
    <div className="login-container">
      <h1>Sign in to your account</h1>
      {message && <h3 className="red">{message}</h3>}
      {errorMessage && <h3 className="red">{errorMessage}</h3>}

      <Form method="post" className="login-form" replace>
        <input name="email" type="email" placeholder="Email address" />
        <input name="password" type="password" placeholder="Password" />
        <button disabled={navigation.state === 'submitting'}>
          {navigation.state === 'submitting' ? 'Logging in...' : 'Log in'}
        </button>
      </Form>
    </div>
  );
}

Error screenshot:

daring skiff
#

I managed to resolve error by modifying error handling in action function -- updated to return an object with 'message' property instead of returning the error message directly, however still successful login not redirecting to '/host' path. Unable to figure out, please help ...

narrow mason