This is the schema for my model:
const workoutSchema = mongoose.Schema({
workouts: [
{
workoutName: String,
sets: Number,
reps: Number,
weight: Number,
},
],
});
This is the postData that is reference in the text field below.
const [postData, setPostData] = useState({
workouts: [{ workoutName: "", sets: "", reps: "", weight: "" }],
});
to access the workoutName above, Below I have set the value to postData.workouts["workoutName"]
seems to work but unsure. I am having trouble on the onChange property, specifically with the second argument in setPostData [workoutName]: e.target.value
. I am having trouble accessing the workoutName
key within the workouts dictionary from the schema.
<TextField
label="Workout"
variant="outlined"
value={postData.workouts["workoutName"]}
onChange={(e) =>
setPostData({ ...postData, workoutName: e.target.value })
}
I have tried workouts["workoutName"]: e.target.value
but I get a syntax error before the bracket saying it was expecting an ,
. error image. I have also tried workouts.workoutName : e.target.value
like in other languages but not worked. How can I access the workoutName in workouts object to reassign it to the value typed in the text field (ie: e.target.value
).
CodePudding user response:
postData is an object
workouts is a property of this object
workout name is a property inside an array that is a property of workouts
So, in order to change the workout name you need to do:
{...postData, workouts: [{...postData.workouts[0], workoutName: e.target.value}]}
To read the workout name you need to do:
postData.workouts[0].name