I have a nested state structure that represents a time entry table. I store an array of TimeEntryRow
objects, where each row object has it's own array of TimeEntry
objects. Note that the objects store an index that represents their position in the table.
export interface TimeState {
timeEntryRows?: TimeEntryRow[];
...
}
export class TimeEntryRow {
rowIndex: number;
timeEntries: TimeEntry[];
...
}
export class TimeEntry {
cellIndex: number;
hours: number;
...
}
I have a reducer that is attempting to update the hours of a single cell in the table, but I'm having some issues getting it to work. With the following action case, the state remains unchanged:
case timeEntryActions.HOURS_CHANGED_ACTION: {
return {
...state,
timeEntryRows: {
...state.timeEntryRows.map(row => {
return row.rowIndex !== action.payload.rowIndex ? row : {
...row,
timeEntries: {
...row.timeEntries.map(te => {
return te.cellIndex !== action.payload.cellIndex ? te : {
...te,
hours: action.payload.hours
}
})
}
}
})
}
}
}
Any help would be greatly appreciated.
Looks like I was accidentally setting my array properties timeEntryRows
and timeEntries
to objects, rather than arrays.
One more reason to avoid nested state as much as possible, as the reducers get longer and more complicated. Ended up using this Redux resource on how to properly update nested objects.
New code:
case timeEntryActions.HOURS_CHANGED_ACTION: {
return {
...state,
timeEntryRows: state.timeEntryRows.map(row => {
return row.rowIndex !== action.payload.rowIndex ? row : {
...row,
timeEntries: row.timeEntries.map(te => {
return te.cellIndex !== action.payload.cellIndex ? te : {
...te,
hours: action.payload.hours
}
})
}
})
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With