Giter Club home page Giter Club logo

ngrx-toolkit's Introduction

NgRx Toolkit

npm

NgRx Toolkit is an extension to the NgRx Signals Store. It is still in beta but already offers following features:

  • Devtools: Integration into Redux Devtools
  • Redux: Possibility to use the Redux Pattern (Reducer, Actions, Effects)
  • Redux Connector: Map NgRx Store Actions to a present Signal Store

To install it, run

npm i @angular-architects/ngrx-toolkit

Devtools: withDevtools()

This extension is very easy to use. Just add it to a signalStore. Example:

export const FlightStore = signalStore(
  { providedIn: 'root' },
  withDevtools('flights'), // <-- add this
  withState({ flights: [] as Flight[] }),
  // ...
);

Redux: withRedux()

withRedux() bring back the Redux pattern into the Signal Store.

It can be combined with any other extension of the Signal Store.

Example:

export const FlightStore = signalStore(
  { providedIn: 'root' },
  withState({ flights: [] as Flight[] }),
  withRedux({
    actions: {
      public: {
        load: payload<{ from: string; to: string }>(),
      },
      private: {
        loaded: payload<{ flights: Flight[] }>(),
      },
    },
    reducer(actions, on) {
      on(actions.loaded, ({ flights }, state) => {
        patchState(state, 'flights loaded', { flights });
      });
    },
    effects(actions, create) {
      const httpClient = inject(HttpClient);
      return {
        load$: create(actions.load).pipe(
          switchMap(({ from, to }) =>
            httpClient.get<Flight[]>(
              'https://demo.angulararchitects.io/api/flight',
              {
                params: new HttpParams().set('from', from).set('to', to),
              },
            ),
          ),
          tap((flights) => actions.loaded({ flights })),
        ),
      };
    },
  }),
);

DataService withDataService()

withDataService() allows to connect a Data Service to the store:

This gives you a store for a CRUD use case:

export const SimpleFlightBookingStore = signalStore(
  { providedIn: 'root' },
  withCallState(),
  withEntities<Flight>(),
  withDataService({
    dataServiceType: FlightService, 
    filter: { from: 'Paris', to: 'New York' },
  }),
  withUndoRedo(),
);

The features withCallState and withUndoRedo are optional, but when present, they enrich each other.

The Data Service needs to implement the DataService interface:

@Injectable({
  providedIn: 'root'
})
export class FlightService implements DataService<Flight, FlightFilter> {
  loadById(id: EntityId): Promise<Flight> { ... }
  load(filter: FlightFilter): Promise<Flight[]> { ... }

  create(entity: Flight): Promise<Flight> { ... }
  update(entity: Flight): Promise<Flight> { ... }
  delete(entity: Flight): Promise<void> { ... }
  [...]
}

Once the store is defined, it gives its consumers numerous signals and methods they just need to delegate to:

@Component(...)
export class FlightSearchSimpleComponent {
  private store = inject(SimpleFlightBookingStore);

  from = this.store.filter.from;
  to = this.store.filter.to;
  flights = this.store.entities;
  selected = this.store.selectedEntities;
  selectedIds = this.store.selectedIds;

  loading = this.store.loading;

  canUndo = this.store.canUndo;
  canRedo = this.store.canRedo;

  async search() {
    this.store.load();
  }

  undo(): void {
    this.store.undo();
  }

  redo(): void {
    this.store.redo();
  }

  updateCriteria(from: string, to: string): void {
    this.store.updateFilter({ from, to });
  }

  updateBasket(id: number, selected: boolean): void {
    this.store.updateSelected(id, selected);
  }

}

DataService with Dynamic Properties

To avoid naming conflicts, the properties set up by withDataService and the connected features can be configured in a typesafe way:

export const FlightBookingStore = signalStore(
  { providedIn: 'root' },
  withCallState({
    collection: 'flight'
  }),
  withEntities({ 
    entity: type<Flight>(), 
    collection: 'flight'
  }),
  withDataService({
    dataServiceType: FlightService, 
    filter: { from: 'Graz', to: 'Hamburg' },
    collection: 'flight'
  }),
  withUndoRedo({
    collections: ['flight'],
  }),
);

This setup makes them use flight as part of the used property names. As these implementations respect the Type Script type system, the compiler will make sure these properties are used in a typesafe way:

@Component(...)
export class FlightSearchDynamicComponent {
  private store = inject(FlightBookingStore);

  from = this.store.flightFilter.from;
  to = this.store.flightFilter.to;
  flights = this.store.flightEntities;
  selected = this.store.selectedFlightEntities;
  selectedIds = this.store.selectedFlightIds;

  loading = this.store.flightLoading;

  canUndo = this.store.canUndo;
  canRedo = this.store.canRedo;

  async search() {
    this.store.loadFlightEntities();
  }

  undo(): void {
    this.store.undo();
  }

  redo(): void {
    this.store.redo();
  }

  updateCriteria(from: string, to: string): void {
    this.store.updateFlightFilter({ from, to });
  }

  updateBasket(id: number, selected: boolean): void {
    this.store.updateSelectedFlightEntities(id, selected);
  }

}

Redux Connector for the NgRx Signal Store createReduxState()

The Redux Connector turns any signalStore() into a Gobal State Management Slice following the Redux pattern.

It supports:

✅ Well-known NgRx Store Actions
✅ Global Action dispatch()
✅ Angular Lazy Loading
✅ Auto-generated provideNamedStore() & injectNamedStore() Functions
✅ Global Action to Store Method Mappers \

Use a present Signal Store

export const FlightStore = signalStore(
  // State
  withEntities({ entity: type<Flight>(), collection: 'flight' }),
  withEntities({ entity: type<number>(), collection: 'hide' }),
  // Selectors
  withComputed(({ flightEntities, hideEntities }) => ({
    filteredFlights: computed(() => flightEntities()
      .filter(flight => !hideEntities().includes(flight.id))),
    flightCount: computed(() => flightEntities().length),
  })),
  // Updater
  withMethods(store => ({
    setFlights: (state: { flights: Flight[] }) => patchState(store,
      setAllEntities(state.flights, { collection: 'flight' })),
    updateFlight: (state: { flight: Flight }) => patchState(store,
      updateEntity({ id: state.flight.id, changes: state.flight }, { collection: 'flight' })),
    clearFlights: () => patchState(store,
      removeAllEntities({ collection: 'flight' })),
  })),
  // Effects
  withMethods((store, flightService = inject(FlightService)) => ({
    loadFlights: reduxMethod<FlightFilter, { flights: Flight[] }>(pipe(
      switchMap(filter => from(
        flightService.load({ from: filter.from, to: filter.to })
      )),
      map(flights => ({ flights })),
    ), store.setFlights),
  })),
);

Use well-known NgRx Store Actions

export const ticketActions = createActionGroup({
  source: 'tickets',
  events: {
    'flights load': props<FlightFilter>(),
    'flights loaded': props<{ flights: Flight[] }>(),
    'flights loaded by passenger': props<{ flights: Flight[] }>(),
    'flight update': props<{ flight: Flight }>(),
    'flights clear': emptyProps()
  }
});

Map Actions to Methods

export const { provideFlightStore, injectFlightStore } =
  createReduxState('flight', FlightStore, store => withActionMappers(
    mapAction(
      // Filtered Action
      ticketActions.flightsLoad,
      // Side-Effect
      store.loadFlights,
      // Result Action
      ticketActions.flightsLoaded),
    mapAction(
      // Filtered Actions
      ticketActions.flightsLoaded, ticketActions.flightsLoadedByPassenger,
      // State Updater Method (like Reducers)
      store.setFlights
    ),
    mapAction(ticketActions.flightUpdate, store.updateFlight),
    mapAction(ticketActions.flightsClear, store.clearFlights),
  )
);

Register an Angular Dependency Injection Provider

export const appRoutes: Route[] = [
  {
    path: 'flight-search-redux-connector',
    providers: [provideFlightStore()],
    component: FlightSearchReducConnectorComponent
  },
];

Use the Store in your Component

@Component({
  standalone: true,
  imports: [
    JsonPipe,
    RouterLink,
    FormsModule,
    FlightCardComponent
  ],
  selector: 'demo-flight-search-redux-connector',
  templateUrl: './flight-search.component.html',
})
export class FlightSearchReducConnectorComponent {
  private store = injectFlightStore();

  protected flights = this.store.flightEntities;

  protected search() {
    this.store.dispatch(
      ticketActions.flightsLoad({
        from: this.localState.filter.from(),
        to: this.localState.filter.to()
      })
    );
  }

  protected reset(): void {
    this.store.dispatch(ticketActions.flightsClear());
  }
}

ngrx-toolkit's People

Contributors

bohoffi avatar manfredsteyer avatar mikezks avatar rainerhahnekamp avatar ricochetbrown avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.