0

I want to call an API in React after a function has been executed.

    const [isVisible, setVisible] = useState(false);
    const [isValid, setValidation] = useState(true);
    const [validationMessage, setValidationMessage] = useState('');

const validate = (callback) => {
        if (code == null || code.trim().length === 0) {
            setValidation(false);
            setValidationMessage(translate.signIn.codeErrorMessage);
            setVisible(true);
        } else if (phoneNumber == null || phoneNumber.trim().length === 0) {
            setValidation(false);
            setValidationMessage(translate.signIn.phoneErrorMessage);
            setVisible(true);
        } 
        callback();
    }

    const authenticate = async () => {
        try {
            return await (authenticateUser.get('/abc', {
                params: {
                    code,
                    phoneNumber,
                }
            }));
        }
        catch (e) {
            setValidationMessage(translate.signIn.exceptionMessage);
            setVisible(true);
        }
    }

    const validateUserCredentials = () => {
        if (isValid) {
            setActivitySpinner(true);
            authenticate().then(response => {
                setActivitySpinner(false);
                const responseData = response.data;
                console.log('responseData', responseData);
                if(responseData.status !== 200) {
                    setVisible(true);
                    setValidationMessage(responseData.message);
                }
                else if(responseData.status === 200) {
                    console.log('success');
                }
            });
        }
    }

  const onSubmit = () => {
        validate(validateUserCredentials);
    }

When I invoke 'onSubmit' function, even if the value of isValid is false. I can see the API is being called. I want to call the function validateUserCredentials only after the function validate has done its task.

Can anyone please tell me what am I doing wrong here?

Sunny
  • 858
  • 3
  • 17
  • 39
  • Your code must be working fine and you may be getting confused with the async nature of state update. Check this answer if it helps https://stackoverflow.com/questions/62846824/react-select-onchange-returning-previous-value-instead-of-current/62846909#62846909 – Rohan Agarwal Jul 19 '20 at 10:04

1 Answers1

1

Ciao, for sure validateUserCredentials is called after validate, maybe you are confused because on validateUserCredentials you see that isValid stills true even if you setted as false. Unfortunately with Hooks you cannot have callback as this.setState to have the certainty that isValid as been setted. What you can do is:

const validate = (callback) => {
    let isvalid_temp = isValid;
    if (code == null || code.trim().length === 0) {
        setValidation(false);
        isvalid_temp = false;
        setValidationMessage(translate.signIn.codeErrorMessage);
        setVisible(true);
    } else if (phoneNumber == null || phoneNumber.trim().length === 0) {
        setValidation(false);
        isvalid_temp = false;
        setValidationMessage(translate.signIn.phoneErrorMessage);
        setVisible(true);
    } 
    callback(isvalid_temp);
}

const validateUserCredentials = (isvalid_temp) => {
    if (isvalid_temp) {
        setActivitySpinner(true);
        authenticate().then(response => {
            setActivitySpinner(false);
            const responseData = response.data;
            console.log('responseData', responseData);
            if(responseData.status !== 200) {
                setVisible(true);
                setValidationMessage(responseData.message);
            }
            else if(responseData.status === 200) {
                console.log('success');
            }
        });
    }
}
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30