5

I have a form inside a route, that if there are any validation errors, it should not allow the user to navigate to another route. If there are no validation errors, then allow navigation to another route.

Below is my current code, which the onBlock function does not work does to its async nature as the functions to submit and then validate the form are asynchronous.

FormComponent.js

import React, { useState, useEffect, useRef } from "react";
import { FieldArray } from "formik";
import { useHistory } from "react-router-dom";
import * as Yup from "yup";
import Form from "./Form";
import TextInput from "./TextInput";

const FormComponent = () => {
  const history = useHistory();
  const [initialValues, setInitialValues] = useState();
  const [isSubmitted, setIsSubmitted] = useState(false);
  const block = useRef();

  const formRef = useRef(null);

  const onFormSubmit = async (values) => {
    setIsSubmitted(true);
  };

  const validationSchema = () => {
    const schema = {
      test: Yup.string().required("Input is Required")
    };
    return Yup.object(schema);
  };

  const onBlock = () => {
    const { submitForm, validateForm } = formRef?.current || {};
    // submit form first
    submitForm()
      .then(() => {
        // then validate form
        validateForm()
          .then(() => {
            // if form is valid - should navigate to route
            // if form is not valid - should remain on current route
            return formRef?.current.isValid;
          })
          .catch(() => false);
      })
      .catch(() => false);
  };

  const redirectToPage = () => {
    history.push("/other-page");
  };

  useEffect(() => {
    block.current = history.block(onBlock);

    return () => {
      block.current && block.current();
    };
  });

  useEffect(() => {
    if (isSubmitted) redirectToPage();
  }, [isSubmitted]);

  useEffect(() => {
    setInitialValues({
      test: ""
    });
  }, []);

  return initialValues ? (
    <Form
      initialValues={initialValues}
      onSubmit={onFormSubmit}
      formRef={formRef}
      validationSchema={validationSchema}
    >
      <FieldArray
        name="formDetails"
        render={(arrayHelpers) =>
          arrayHelpers && arrayHelpers.form && arrayHelpers.form.values
            ? (() => {
                const { form } = arrayHelpers;
                formRef.current = form;
                return (
                  <>
                    <TextInput name="test" />
                    <button type="submit">Submit</button>
                  </>
                );
              })()
            : null
        }
      />
    </Form>
  ) : null;
};

export default FormComponent;

If a user tries to submit the form without any value in the input, I would expect that onBlock would return false to block navigation. But this does not seem to work. Simply returning false in the onBlock function does however. So it seems that the history.block function does not accept any callbacks. I have also tried to convert it to an async function and await the submitForm & validateForm functions, but still no joy. Is there a way around this? Any help would be greatly appreciated.

Here is CodeSandbox with an example.

1 Answer 1

12

The history.block function accepts a prompt callback which you can use to prompt the user or do something else in response to the page being blocked. To block the page you just need to call history.block() more info here.

The formik form is validated when you try to submit it and if it successfully validates then it proceeds to submit the form, this is when onSubmit callback will be called. So if you'd like to block the page when there are validation errors you can use the formik context to subscribe to the validation isValid and whenever that is false block.

const useIsValidBlockedPage = () => {
  const history = useHistory();
  const { isValid } = useFormikContext();

  useEffect(() => {
    const unblock = history.block(({ pathname }) => {
      // if is valid we can allow the navigation
      if (isValid) {
        // we can now unblock
        unblock();
        // proceed with the blocked navigation
        history.push(pathname);
      }
      // prevent navigation
      return false;
    });

    // just in case theres an unmount we can unblock if it exists
    return unblock;
  }, [isValid, history]);
};

Here is a codesandbox for that adapted from yours. I removed some components that weren't needed.

Another solution is validating manually on all page transitions and choosing when to allow the transition yourself and in this case it is if validateForm returns no errors.

// blocks page transitions if the form is not valid
const useFormBlockedPage = () => {
  const history = useHistory();
  const { validateForm } = useFormikContext();

  useEffect(() => {
    const unblock = history.block(({ pathname }) => {
     // check if the form is valid
      validateForm().then((errors) => {
        // if there are no errors this form is valid
        if (Object.keys(errors).length === 0) {
          // Unblock the navigation.
          unblock();
          // retry the pagination
          history.push(pathname);
        }
      });
      // prevent navigation
      return false;
    });
    return unblock;
  }, [history, validateForm]);
};

And the codesandbox for that here

3
  • I initially had something similar, but the isValid value is true initially, so if you go to another route without editing the form, it will allow navigation, despite not filling in the form. This is what I want to avoid.
    – mcclosa
    Commented Mar 9, 2021 at 16:56
  • so you want to prevent going to another route until the form is submitted with valid content? <- if thats the case just add in the submitCount to the logic. Commented Mar 9, 2021 at 18:08
  • If you're on a newer version of formik you can also add the validateOnMount={true} prop Commented Mar 10, 2021 at 1:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.