1

I'm trying to validate the phone field, to get all letters and dots with the code below.

validatePhone = () => {
        const sanitizedPhone = this.state.phone.replace(/\D/g, '');
        if (sanitizedPhone.length >= 10 && sanitizedPhone.length <= 11) {
            this.setState({ phone: sanitizedPhone });
            return true;
        }
        toast.error('Invalid phoneNumber.', {
            position: "top-center",
            autoClose: false,
            closeOnClick: true,
        });
        return false;
    }

When i trying console.log(sanitizedPhone) with dots in input like 11.97.4.4.51234 i get 11974451234 but after this, on console.log(this.state.phone) i get the older number 11.97.4.4.51234

5
  • setState doesn't always update instantly. Console.log in you render method. Commented Dec 26, 2019 at 18:23
  • @its4zahoor i get the same error on submit form Commented Dec 26, 2019 at 18:34
  • You're using arrow function so this inside it would have the same value just as before you assigned it. Commented Dec 26, 2019 at 18:51
  • When i use with callback @awran5, i got the same error Commented Dec 26, 2019 at 19:03
  • @LuizHenrique then please share complete relevant code or codesandbox. either you input field is not bind with state or your form data is not updating. Commented Dec 28, 2019 at 9:49

1 Answer 1

2

From react docs:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.

This is why you don't see your change right after you're using setState.

Sign up to request clarification or add additional context in comments.

6 Comments

So what's the best way to handle this phone data and play at State?
what would you like to do with the sanitized phone number? can you provide more code of what you're trying to do? you can use this codesandbox.io/s/youthful-microservice-kqxcx
Since my country has some numbers with the 9 digit in front of the number, such as 11 95879-5791 or 11 8597-1346, I am trying to avoid having space, period or comma in the form.
@LuizHenrique I created this sample with functional component, is this the behavior you're looking for ? codesandbox.io/s/pedantic-elion-39iri
@LuizHenrique try now
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.