2

I am not new to react, but for some weird reason, I have came across a quick example I was testing, and I noticed that the state is coming out empty string. as if it were not updating. I am using react 18.1, and here is a stack blitz instance to see the code live (a sandbox), click me.

Full code:

import React, { useState } from 'react';

export default function App() {
  const [qr, setQr] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    alert('The submitted QR code is: ', qr);
  };

  const handleChange = (e) => {
    setQr(e.target.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input onChange={handleChange} value={qr} />
    </form>
  );
}

can anyone please explain why the state is not ready when submitting the form? and how do you work this out?

I was actually working on a larger project, and when I came across this bug, I decided to demonstrate this in a smaller quick example in a sandbox.

Thanks yous 👍

2 Answers 2

5

The issue is in your alert. The value is actually being updated on change, but alert only takes a single argument and you're passing it two.

Instead, you can concatenate the string like so to produce the desired result:

alert(`The submitted QR code is: ${qr}`);
Sign up to request clarification or add additional context in comments.

Comments

1

alert should return a string, so you should give it a string:

 alert('The submitted QR code is: ', qr);
 // the ',' is not for concat

 // use instead:
 alert(`The submitted QR code is: ${qr}`);
 //or
 alert('The submitted QR code is: ' + qr);

Comments

Your Answer

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