Following is my js file which is setting two times, starting time and ending times saving them in startTime useState and endTime useState. The thing is that now i want to use the add button to add more time slots in a single day. For that I made my startTime obj of keys and values as arrays. As i press the add button i want to add more time slots in the appendable arrays in setStartTime and setEndTime(yet to do). Following is the code:
import React, { useState, useEffect } from "react";
import DateFnsUtils from "@date-io/date-fns"; // choose your lib
import { TimePicker, MuiPickersUtilsProvider } from "@material-ui/pickers";
import CheckBox from "./CheckBox";
import IconButton from "@material-ui/core/IconButton";
import RemoveIcon from "@material-ui/icons/Remove";
import AddIcon from "@material-ui/icons/Add";
import "../compStyles/SetTime.css";
import { indexOf, times } from "lodash";
function Doctor() {
const [startTime, setStartTime] = useState({
Monday: [null],
Tuesday: [null],
Wednesday: [null],
Thursday: [null],
Friday: [null],
Saturday: [null],
Sunday: [null],
});
const [endTime, setEndTime] = useState({
Monday: null,
Tuesday: null,
Wednesday: null,
Thursday: null,
Friday: null,
Saturday: null,
Sunday: null,
});
const handleAddFields = (i) => {
setStartTime([...startTime, { Monday: null }]);
console.log(i);
};
const handleTimeChange = (weekday, startEnd, time, index) => {
switch (startEnd) {
case "start":
setStartTime(state => ({
...state,
weekday:[...state.weekday, [index]:time]
}))
console.log("GODDAMN",startTime[weekday[index]]);
break;
case "end":
setEndTime({ ...endTime, [weekday]: time });
break;
default:
break;
}
};
let items = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
];
return (
<div>
<ul>
{items.map((item) => {
return (
<li>
<CheckBox /> <h1>{item}</h1>{" "}
{startTime[item].map((i) => {
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<TimePicker
className="timepicker1"
value={startTime[item[indexOf(i)]]}
onChange={(event) =>
handleTimeChange(item, "start", event, indexOf(i))
}
/>
<h1>-</h1>
<TimePicker
value={endTime[item]}
onChange={(event) => handleTimeChange(item, "end", event)}
/>
</MuiPickersUtilsProvider>
);
})}
<div className="icons">
<IconButton>
<RemoveIcon />
</IconButton>
<IconButton onClick={(item) => handleAddFields(item)}>
<AddIcon />
</IconButton>
</div>
</li>
);
})}
</ul>
</div>
);
}
export default Doctor;
This image is before i set the starting time : main UI
CodePudding user response:
state.weekday
isn't iterable because it's undefined. state.weekday
gets the value of the property with the name weekday
on the object state
. state[weekday]
gets the value of the property whose name is the value of the variable weekday. In this case you want the later. Also note that you probably want
[weekday]: [...
Not
weekday: [...
Remember brackets if you want the object to behave like a map, periods if you want it to behave like an object.