Created
June 12, 2022 13:02
-
-
Save romgrk/6aac91df09cdebf8a0761b9fb3afd20e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // With immer | |
| export const slice = createSlice({ | |
| name: 'report', | |
| initialState: createEmptyStore<StoredReport>(), | |
| reducers: { | |
| setMetric: (state, action) => { | |
| const { id, metricId, metric: newMetric } = action.payload | |
| state.byId[id].metrics = | |
| state.byId[id].metrics?.map(metric => | |
| metric.id !== metricId ? | |
| metric : | |
| { ...metric, ...newMetric } | |
| ) | |
| }, | |
| }, | |
| }) | |
| // With immer + original() | |
| export const slice = createSlice({ | |
| name: 'report', | |
| initialState: createEmptyStore<StoredReport>(), | |
| reducers: { | |
| setMetric: (draft, action) => { | |
| const { id, metricId, metric: newMetric } = action.payload | |
| const state = original(draft) | |
| const lens = lensPath(['byId', id, 'metrics']) | |
| const newState = | |
| over( | |
| lens, | |
| metrics => metrics.map(metric => | |
| metric.id === metricId ? | |
| { ...metric, ...newMetric } : | |
| metric | |
| ), | |
| state | |
| ) | |
| return newState | |
| }, | |
| }, | |
| }) | |
| // Without immer | |
| export const slice = createSlice({ | |
| name: 'report', | |
| initialState: createEmptyStore<StoredReport>(), | |
| reducers: createReducers(), | |
| }) | |
| const { setMetric } = addRawReducers(slice, { | |
| setMetric: (state, action) => { | |
| const { id, metricId, metric: newMetric } = action.payload | |
| const lens = lensPath(['byId', id, 'metrics']) | |
| const newState = | |
| over( | |
| lens, | |
| metrics => metrics.map(metric => | |
| metric.id === metricId ? | |
| { ...metric, ...newMetric } : | |
| metric | |
| ), | |
| state | |
| ) | |
| return newState | |
| } | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment