Skip to content

Instantly share code, notes, and snippets.

@romgrk
Created June 12, 2022 13:02
Show Gist options
  • Select an option

  • Save romgrk/6aac91df09cdebf8a0761b9fb3afd20e to your computer and use it in GitHub Desktop.

Select an option

Save romgrk/6aac91df09cdebf8a0761b9fb3afd20e to your computer and use it in GitHub Desktop.
// 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