简体   繁体   中英

How to export value to another const

I'm using react-google-recaptcha to generate invisible ReCaptcha and I need to use the token in another const.

The token is generating correctly, but I don't know how to pass it on to another location. How should I do this?

   const onTextSubmit = async () => {
        let recaptchaToken;
        if (recaptchaLoaded) {
          recaptchaToken = await recaptcha.current.execute();
        }
        
        // How to export recaptchaToken?
      };

I need to get the recaptchaToken and use it here:

  const onSubmit: SubmitHandler<FormInput> = (data) => {
    formCreateMutation.mutate({
      data,
      recaptchaToken,
    });
  };

The two const are in the same file, I'm using react to do that.

Thanks!!

You are not posting all code from the component but you can store the recaptchaToken value in react state like this:

export default function App() {
  const [recaptchaToken, setRecaptchaToken] = useState(undefined);

  const onTextSubmit = async () => {
    if (recaptchaLoaded) {
      const value = await recaptcha.current.execute();
      setRecaptchaToken(value);
    }
    
    // How to export recaptchaToken?
  };

  const onSubmit: SubmitHandler<FormInput> = (data) => {
    if (recaptchaToken) {
      formCreateMutation.mutate({
        data,
        recaptchaToken,
      });
    }
  };

  return (
    <div className="App">
      <h1>{recaptchaToken}</h1>
    </div>
  );
}

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