7.0.1 • Published 3 years ago

ngrx-etc v7.0.1

Weekly downloads
1,643
License
MIT
Repository
github
Last release
3 years ago

NgRx-etc

All Contributors

mutableOn

Without the mutableOn function our entityReducer would look something like this.

const entityReducer = createReducer<{ entities: Record<number, { id: number; name: string }> }>(
  {
    entities: {},
  },
  on(create, (state, { type, ...entity }) => ({
    ...state,
    entities: { ...state.entities, [entity.id]: entity }
  }),
  on(update, (state, { id, newName }) => {
    const entity = state.entities[id]

    if (entity) {
      return {
        ...state,
        entities: {
          ...state.entities,
          [entity.id]: { ...entity, name: newName }
        }
      }
    }

    return state;
  },
  on(remove, (state, { id }) => {
    const { [id]: removedEntity, ...rest } = state.entities;

    return { ...state, entities: rest };
  }),
)

With the mutableOn function we are able to directly perform state mutations in reducers with less noise, and more concise code.

const entityReducer = createReducer<{ entities: Record<number, { id: number; name: string }> }>(
  {
    entities: {},
  },
  mutableOn(create, (state, { type, ...entity }) => {
    state.entities[entity.id] = entity
  }),
  mutableOn(update, (state, { id, newName }) => {
    const entity = state.entities[id]
    if (entity) {
      entity.name = newName
    }
  }),
  mutableOn(remove, (state, { id }) => {
    delete state.entities[id]
  }),
)

mutableReducer

For when you want to go all-in! Does work with the NgRx on method, as well as the mutableOn method. The only difference is that it's needed to return the state with the on method.

const entityReducer = createMutableReducer<{ entities: Record<number, { id: number; name: string }> }>(
  {
    entities: {},
  },
  on(create, (state, { type, ...entity }) => {
    state.entities[entity.id] = entity

    // explicit return state with `on`
    return state
  }),
  on(update, (state, { id, newName }) => {
    const entity = state.entities[id]
    if (entity) {
      entity.name = newName
    }

    // explicit return state with `on`
    return state
  }),
  mutableOn(remove, (state, { id }) => {
    delete state.entities[id]
    // don't have to return state with `mutableOn`
  }),
)

Contributors ✨

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!

7.0.1

3 years ago

6.0.0

3 years ago

5.0.2

3 years ago

5.0.1

4 years ago

5.0.0

4 years ago

4.1.0

4 years ago

4.0.0

4 years ago

3.0.0

4 years ago

2.1.0

5 years ago

2.0.0

5 years ago

1.4.1

5 years ago

1.4.0

5 years ago

1.3.0

5 years ago

1.2.0

5 years ago

1.1.0

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago