reactjsnpmuse-effectformikmaskedinput

Formik setFormValues not working inside useEffect


I have the following code:

import React, { useEffect, useState } from "react";
import { Formik, Field } from "formik";
import MaskedInput from "react-text-mask";

const phoneNumberMask = [ "(", /[1-9]/, /\d/, /\d/, ")", " ", /\d/, /\d/, /\d/, "-", /\d/, /\d/, /\d/, /\d/ ];

export default () => {

  const [formValues, setFormValues] = useState(null);

  useEffect(() => {
    setTimeout(() => {
      setFormValues({ phone: '9178889999' });
    }, 1000)
  }, []);

  const onSubmit = (values) => {
    console.log(values);
  };

  return (
    <div className="app">
      <Formik
        initialValues={{ phone: '9134445555' }}
        onSubmit={onSubmit}
        enableReinitialize
      >
        {props => {
          const {
            handleChange,
            handleSubmit,
          } = props;
          return (
            <form onSubmit={handleSubmit}>
              <Field name="phone">
                {
                  ({ field }) => <MaskedInput
                    {...field}
                    type="text"
                    mask={phoneNumberMask}
                    placeholder="Enter your phone number"
                    onChange={handleChange}
                    className="text-input"
                  />
                }
              </Field>
              <button type="submit">
                Submit
              </button>
            </form>
          );
        }}
      </Formik>
    </div>
  );
};

where the MaskedInput gets initially populated with value: 9134445555 using format: (913) 444-5555.

My problem is: The call to: setFormValues(...) doesn't work from inside: useEffect after a timeout of 1 s (1000 ms).

My Goals

  1. The MaskedInput gets populated with second value: 9178889999 after 1 s.
  2. The MaskedInput shows the second value with proper format: (917) 888-9999.

Solution

  • Here is the simplest way to achieve both goals on the code above:

    1. Change: initialValues={{ phone: '9134445555' }} to: initialValues={ formValues || { phone: '9134445555' } }

    2. On the package.json change: "react-text-mask": "^5.4.3" to "react-text-mask": "5.4.1".

    If we use latest version as of today: 5.4.3 then the pattern won't be applied on value change. This issue happens from version: 5.4.2. That issue doesn't exist on version: 5.4.1, though. That's why I use that version.

    By the way this library seems to be not maintained since: July 2018.