Luiz Henrique
Luiz Henrique

Reputation: 103

Validate phone number on React.js

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

Upvotes: 1

Views: 1636

Answers (1)

Morta1
Morta1

Reputation: 619

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.

Upvotes: 2

Related Questions