Home > Enterprise >  React state is empty when submitting the form
React state is empty when submitting the form

Time:12-15

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

  • Related