简体   繁体   中英

React useState value not updated in ref callback

I have a functional component called SignUp it uses google recaptcha to secure the signup form.

Signup creates a ref pointing to the Recaptcha component and declares a callback function onResolved that points to a function method onRecaptchaResolved

The problem is that when onRecaptchaResolved is called after Recaptcha execution the value of our input is not the lastest state but the initial value set by useState in our case "hi"

import React, { useState } from 'react';
import styled from 'styled-components';
import Recaptcha from 'react-google-invisible-recaptcha';

const Input = styled.input``

function SignUp({dispatch}) {
    const [inputValue, setInputValue] = useState("hi");
    let recaptcha = null; // this will be our ref

    const formSubmit = () => {
         recaptcha.execute()
    }

    const onRecaptchaResolved = ( recaptchaToken) => {
         console.log(inputValue); // always logs; "hi"
    }


    return (
        <>          
            <Input 
                placeholder="you@example.com"
                type="text"
                value={inputValue}
                onChange={e => setInputValue(e.target.value)
                }
            />
            <Recaptcha
                ref={ ref => recaptcha = ref }
                sitekey={ "{MY_SITE_KEY}" }
                onResolved={recaptchaToken =>{ onRecaptchaResolved(recaptchaToken)} } 
            />

            <SubmitButton onClick={formSubmit}> Submit email</SubmitButton>
        </>
    )
}

How do I ensure that the input value read in onRecaptchaResolved is the updated value?

react-google-invisible-recaptcha seems to store the initial value provided in onResolved and won't update it unless <Recaptcha> is re-mounted. See https://github.com/szchenghuang/react-google-invisible-recaptcha/blob/master/src/index.js#L41

The easiest way to confirm this is to set a key on <Recaptcha> that changes whenever inputValue changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM