2

Given a reducer example like the following

_({
  expandAbility: (state, a: { which: string }) => ({
    ...state,
    report: state.report && {
      waitingForIt: false,
      content: state.report.content && {
        ...state.report.content,
        interaction: {
          expandAbilities: !state.report.content.interaction.expandAbilities.contains(a.which)
            ? state.report.content.interaction.expandAbilities.add(a.which)
            : state.report.content.interaction.expandAbilities.remove(a.which)
        }
      }
    }
  }),
})

(state type given below just for question context purposes)

const initialState = {
  report: undefined as
    | {
        waitingForIt?: boolean
        content?: {
          supportedFightIds: number[]
          deathCut: number
          reportInfo: any
          deathsFull: any
          deathsByPlayer: any
          deathsByAbility: any
          interaction: {
            expandAbilities: Set<string>
          }
        }
      }
    | undefined,
  error: undefined as Error | undefined
}

Is there any kind of trick or "flavor-of-the-moment" library which would allow me to write a reducer update operation like expandAbility in a shorter way? (besides maybe creating some vars to reference inner paths)

2 Answers 2

1

There are lots of immutable update utilities out there, check out some options at https://github.com/markerikson/redux-ecosystem-links/blob/master/immutable-data.md#immutable-update-utilities and see what would be the best fit for you. For starters check out Immutability-helper or immer.

Sign up to request clarification or add additional context in comments.

Comments

1

So there are two things you could do to help simplify this. The first thing I like to do is move the logic out of the reducer and instead just pass in a value and say set expandAbilities to action. expandAbilities.

The second is actually something we do at work. We use immutableJS and wrote a single reducer that handles all of our state calls because you can give it a path of the parts of state that need to be updated and the value to update it with so we extracted that out and now it is easy to say dispatch(actions.update({path: ['report', 'content', 'interaction', 'expandAbilities'], value: '123' }))

You can even expand this so you can pass in a list of values that need to be updated and even preform validations around the data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.