I’m creating an app that asks users for some input. The values from the forms are stored in a state. The problem here is when I used the onChange handler to log the current state, it’s always a step behind.
This is my current situation.
import React, { useState, useEffect } from "react";
export const Formitems = (props) => {
const [formData, setFormData] = useState({ difficulty: "easy", limit: "20" });
const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prev) => ({
...prev,
[name]: value,
}));
};
return (
<div>
<div>
<span>Difficulty:</span>
<select
name="difficulty"
value={formData.difficulty}
onChange={handleChange}
>
<option value="easy">Easy</option>
<option value="medium">Medium</option>
<option value="hard">Hard</option>
</select>
</div>
<div>
<span>No. of Questions (Max. 20): {formData.limit}</span>
<input
type="range"
min="1"
name="limit"
value={formData.limit}
max="20"
onChange={handleChange}
/>
</div>
</div>
);
};