Reputation: 177
I have the following data structure in my state
this.state = {
days: [
{ day: "Monday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
{ day: "Tuesday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
{ day: "Wednesday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
{ day: "Thursday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
{ day: "Friday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
{ day: "Saturday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
{ day: "Sunday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
],
}
I am expecting a response from the server with the same format availabilities
array (coming from props).
If the day of the received array matches, I want to overwrite and setState to only those days that get returned. The rest to stay the same. For example if the response is:
{ day: "Monday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30 },
I want to setState to the first element of my days array and overwrite fromHour, toHour, fromMin, toMin and set available to true. Here's my below, and the setState where I am currently stuck. Help or suggestions?
setAvailabilities() {
const { availabilities } = this.props;
const { days } = this.state;
const weekday = [];
const daysAailable = [];
for (i = 0; i < availabilities.length; i++) {
for (j = 0; j < days.length; j++) {
if (days[j].day === availabilities[i].day) {
this.setState({
...this.state.days,
//stuck here
})
}
}
}
}
Upvotes: 0
Views: 80
Reputation: 736
The datastructure for your state is:
interface State {
days: Day[]
}
But inside the this.setState
call, you're spreading the array across the state instead of replacing the array. So you would end up with something like this:
state = {
days: [...],
0: { day: "Monday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
1: { day: "Tuesday", fromHour: 11, fromMin: 30, toHour: 17, toMin: 30, available: false },
// etc...
}
Anyway...
Instead of calling this.setState
for each updated day, I would recommend constructing a new array and set the entire date array at once:
setAvailabilities() {
const { availabilities } = this.props;
const { days } = this.state;
const nextDays = [...days]
for (i = 0; i < availabilities.length; i++) {
for (j = 0; j < nextDays.length; j++) {
if (nextDays[j].day === availabilities[i].day) {
nextDays[j] = availabilities[i]
}
}
}
this.setState({ days: newDays })
}
Upvotes: 2