search

Home  >  Q&A  >  body text

Use useState to set the value entered in the form

<p>I'm trying to use useState to set the value of an input, but it's not working the way I want. </p> <p>So I created a weekly schedule using Formik for an appointment system. I have a radio button for free appointments. When selected, I get the time data for the appointment. But I didn't get this day. So I tried adding another input to get daily data. I set the entered value to the state. When the radio button is selected it sets the date. But onSubmit I get the initial value instead of the newly set value. Interestingly, when I try to write something in the input, it returns the value I want for the last key I pressed. But if I do nothing it just returns the initial value. </p> <p>Initial value of my form:</p> <pre class="brush:php;toolbar:false;">const [day, setDay] = useState("Gün"); <Formik onSubmit={handleFormSubmit} initialValues={{ firstname: "", lastname: "", email: "", date: "", day: day, }} ></pre> <p>I set the status of the radio button: </p> <pre class="brush:php;toolbar:false;"><Field type="radio" name="date" value={x.monPm3Time} onClick={() => { setDay("Pazartesi"); }} /></pre> <p>The value of my input is set to state:</p> <pre class="brush:php;toolbar:false;"><Field id="day" name="day" value = {day} /></pre> <p>My handleSubmit function (I'm just logging them now to see if it works): </p> <pre class="brush:php;toolbar:false;">const handleFormSubmit = async (values) => { console.log(values); // fetch("http://localhost:5000/api/appointment", { // method: "POST", // body: values, // headers: { // Authorization: "Bearer " token, // }, // }) // .then((res) => { // console.log(res.status); // }) // .catch((err) => { // console.log(err); // }); }</pre></p>
P粉588660399P粉588660399451 days ago606

reply all(1)I'll reply

  • P粉046878197

    P粉0468781972023-09-05 21:40:16

    So I tried replicating (to the best of my ability) your problem in the code editor and I was able to change the text in the input when the radio button is clicked. You can find my implementation here: https://stackblitz.com/edit /react-b5rvzg?file=src/App.js

    I also believe you are not passing anything to your handleFormSubmit function, so you won't see anything. I could be wrong as I don't fully understand how your code is set up

    reply
    0
  • Cancelreply