problem lies in this code:
whenever i ented any value into my added input, for exmaple like 15 or any number. im able to remove 5 but not 1, or any first number.
here i will link demo. test acc is autofilled if need.
https://wemove-ochre.vercel.app/gym/chest/Bench_press_a7864ba8-fe09-4605-b9a3-9e4ea9d3ddfc
thank you for your time and help in advance.
const set = {
id: uuidv4(),
weight: 0,
rep: 0,
};
const defaultSets = [
set,set,set
];
const defaultCardioSets = [set];
const [sets, setSets] = useState<Set[]>(
type === "cardio" ? defaultCardioSets : defaultSets
);
const [allWeights, setAllWeights] = useState(0);
function handleAddSet(e: React.MouseEvent<HTMLButtonElement>) {
e.preventDefault();
setSets([...sets, set]);
}
function handleUpdatePerformance(
e: React.ChangeEvent<HTMLInputElement>,
id: string
) {
e.preventDefault();
const newValue = parseFloat(e.target.value);
if (isNaN(newValue)) return;
const updatedValue = newValue === 0 ? 0 : newValue;
const updatedSets = sets.map((set) => {
if (set.id === id) {
return { ...set, weight: updatedValue };
}
return set;
});
setSets(updatedSets);
}
{sets.map((set, i) => (
<div key={set.id} className="flex gap-2 items-center justify-between">
<label className="w-1/4" htmlFor={`set_${i}_metric`}>
{`Set ${i + 1}`}:{" "}
</label>
<input
id={`set_${i}_metric`}
type="number"
className="px-2 py-1 w-1/4 my-2"
placeholder={exercise.metric}
value={set.weight === 0 ? "" : set.weight}
required
onChange={(e) => handleUpdatePerformance(e, set.id)}
/> ))}
i have tried using input as text and pass default as string. but it wont let me go back to empty string.
2
Answers
So when you try to remove your input entirely the e.target.value will be an empty string, when that is parsed to float it will return as NaN which then exits out of the function without ever changing the value
Instead you can add a condition to check if the new value is an empty string by changing
to
Your code at parseFloat("") must be returning the function as it will be returning NAN, making your last character not get updated/removed
You might want to try something like this