Reputation: 947
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
MaskedInput
gets populated with second value: 9178889999
after 1 s
.MaskedInput
shows the second value with proper format: (917) 888-9999
.Upvotes: 1
Views: 1881
Reputation: 947
Here is the simplest way to achieve both goals on the code above:
Change: initialValues={{ phone: '9134445555' }}
to: initialValues={ formValues || { phone: '9134445555' } }
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
.
Upvotes: 1
Reputation: 745
The issue is simple, you didn't wire formValues
to your initialValues
.
This leads to another issue, your mask is not updating properly : React Form value not updating when toggling InputMask mask.
Upvotes: 1