Next.js Discord

Discord Forum

router.replace after form submit not working

Unanswered
simpros posted this in #help-forum
Open in Discord
Hi 👋

I have a problem with next/navigation router. It only lets me replace the href after a full-page reload.

'use client';

import { yupResolver } from '@hookform/resolvers/yup';
import { TextInput } from '@pioz/mlm-form-fields';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { object, string } from 'yup';

export function TwoFaVerify({
  bearer,
  redirectTo,
}: {
  bearer: string;
  redirectTo: string;
}) {
  const router = useRouter();

  const pinSchema = object().shape({
    pin: string().required('Pin is required'),
  });

  const {
    register,
    handleSubmit,
    setError,
    formState: { isValid, errors },
  } = useForm<{ pin: string }>({
    reValidateMode: 'onChange',
    resolver: yupResolver(pinSchema),
  });

  const onSubmit = async (val: { pin: string }) => {
    const formData = new FormData();
    formData.append('pin', val.pin);
    const response = await fetch(process.env.NEXT_PUBLIC_2FA_LOGIN!, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${bearer}`,
      },
      body: formData,
    });

    if (response.status !== 200) {
      setError('pin', {
        message: 'Invalid pin',
      });
    }

    if (response.ok) {
      // TEMP FIX
      window.location.href = redirectTo;
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <h3 className="font-bold text-lg">Two-Factor Authentication</h3>
      <p className="py-4">
        Enter the six digit code from your authentication app
      </p>
      <TextInput
        autoFocus={true}
        register={register('pin')}
        label="Pin"
        error={errors.pin}
      />
      <button type="submit" className="btn btn-primary" disabled={!isValid}>
        Submit
      </button>
    </form>
  );
}


Any idea why this happens? I get to this page only if two-factor is enabled

0 Replies