Hi I'm new to react and I'm trying to make a workout tracker but I have become hardstuck on trying to capture the input of the exercises the way I'd like, as you can see by the many commented out code blocks I think that I'm missing something fundamental with useState maybe?
this is my useState
const [formData, setFormData] = useState({
title: "",
date: "",
exercises: [{ Exercise: "benchpress", Reps: "5", Sets: "5" }],
});
this works with the title and date but i've tried many approaches and cant get it work with the object inside the exercise array
this is the onChange function on the form inputs
const updateForm = (e) => {
setFormData((currentFormData) => ({
...currentFormData,
[e.target.name]: e.target.value,
}));
All the solutions I've tried has just led to adding whole new objects to the exercises array, or just adding the name value in the original object next to the title and date.
CodePudding user response:
setFormData(formData.map((line, i) => {
line.title= "";
line.date="",
line.exercises.map((lineExerc, j) => {
lineExerc.name = e.target.value;
});
return line;
}));
CodePudding user response:
hey try like this it will update your exercise name and you can add more input fields to update more values
import * as React from 'react'
const Comp = () => {
const [formData, setFormData] = React.useState({
title: '',
date: '',
exercises: [{ Exercise: 'benchpress', Reps: '5', Sets: '5' }]
})
React.useEffect(() => {
console.log('gg', formData)
}, [formData])
const handle = (e, type) => {
console.log('gg', e)
setFormData({
title: formData.title,
date: formData.date,
exercises: [
{
Exercise: type === 'E' ? e : formData.exercises[0].Exercise,
Reps: type === 'R' ? e : formData.exercises[0].Reps,
Sets: type === 'S' ? e : formData.exercises[0].Sets
}
]
})
}
return (
<>
<input onChange={(e) => handle(e.target.value, 'E')} />
<input placeholder="rep" onChange={(e) => handle(e.target.value, 'R')} />
<input onChange={(e) => handle(e.target.value, 'S')} />
</>
)
}
Not the best way but it works For an array with large number of objects/feilds you should use map instead of hard coding them