npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ngrx-rtk-query

v17.4.6

Published

Angular RTK Query

Downloads

1,354

Readme

MIT All Contributors

ngrx-rtk-query is a plugin to make RTK Query (including auto-generated hooks) works in Angular applications with NgRx!! Mix the power of RTK Query + NgRx + Signals to achieve the same functionality as in the RTK Query guide with hooks.

Table of Contents

Installation

npm install ngrx-rtk-query

Versions

| Angular / NgRx | ngrx-rtk-query | @reduxjs/toolkit | Support | | :------------: | :----------------: | :--------------: | :-----------------: | | 17.x | >=17.3.x (signals) | ~2.2.1 | Bugs / New Features | | 17.x | >=17.1.x (signals) | ~2.2.1 | Bugs | | 16.x | >=4.2.x (rxjs) | ~1.9.3 | Critical bugs | | 15.x | 4.1.x (rxjs) | 1.9.3 | None |

Only the latest version of Angular in the table above is actively supported. This is due to the fact that compilation of Angular libraries is incompatible between major versions.

Basic Usage

You can follow the official RTK Query guide with hooks, with slight variations. You can see the application of this repository for more examples.

Start by importing createApi and defining an "API slice" that lists the server's base URL and which endpoints we want to interact with:

import { createApi, fetchBaseQuery } from 'ngrx-rtk-query';

export interface CountResponse {
  count: number;
}

export const counterApi = createApi({
  reducerPath: 'counterApi',
  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  tagTypes: ['Counter'],
  endpoints: (build) => ({
    getCount: build.query<CountResponse, void>({
      query: () => ({
        url: `count`,
      }),
      providesTags: ['Counter'],
    }),
    incrementCount: build.mutation<CountResponse, number>({
      query: (amount) => ({
        url: `increment`,
        method: 'PUT',
        body: { amount },
      }),
      invalidatesTags: ['Counter'],
    }),
    decrementCount: build.mutation<CountResponse, number>({
      query: (amount) => ({
        url: `decrement`,
        method: 'PUT',
        body: { amount },
      }),
      invalidatesTags: ['Counter'],
    }),
  }),
});

export const { useGetCountQuery, useIncrementCountMutation, useDecrementCountMutation } = counterApi;

Add the api to your store in your app or in a lazy route.

import { provideStoreApi } from 'ngrx-rtk-query';
import { counterApi } from './route/to/counterApi.ts';

bootstrapApplication(AppComponent, {
  providers: [
    ...

    provideStoreApi(counterApi),
    // Or to disable setupListeners:
    // provideStoreApi(counterApi, { setupListeners: false })

    ...
  ],
}).catch((err) => console.error(err));

Use the query in a component

import { useDecrementCountMutation, useGetCountQuery, useIncrementCountMutation } from '@app/core/api';

@Component({
  selector: 'app-counter-manager',
  template: `
    <section>
      <button [disabled]="increment.isLoading()" (click)="increment(1)">+</button>

      <span>{{ countQuery.data()?.count ?? 0 }}</span>

      <button [disabled]="decrement.isLoading()" (click)="decrement(1)">-</button>
    </section>
  `,
})
export class CounterManagerComponent {
  countQuery = useGetCountQuery();
  increment = useIncrementCountMutation();
  decrement = useDecrementCountMutation();
}

Usage with HttpClient or injectable service

You can use the fetchBaseQuery function to create a base query that uses the Angular HttpClient to make requests or any injectable service. Basic HttpClient example:


const httpClientBaseQuery = fetchBaseQuery((http = inject(HttpClient), enviroment = inject(ENVIRONMENT)) => {
  return async (args, { signal }) => {
    const {
      url,
      method = 'get',
      body = undefined,
      params = undefined,
    } = typeof args === 'string' ? { url: args } : args;
    const fullUrl = `${enviroment.baseAPI}${url}`;

    const request$ = http.request(method, fullUrl, { body, params });
    try {
      const data = await lastValueFrom(request$);
      return { data };
    } catch (error) {
      return { error: { status: (error as HttpErrorResponse).status, data: (error as HttpErrorResponse).message } };
    }
  };
});

export const api = createApi({
  reducerPath: 'api',
  baseQuery: httpClientBaseQuery,
//...

Usage

Queries

The use of queries is a bit different compared to the original Queries - RTK Query guide. You can look at the examples from this repository.

The parameters and options of the Query can be signals or static. You can update the signal to change the parameter/option.

The hook useXXXQuery() returns a signal with all the information indicated in the official documentation (including refetch() function). Can be used as an object with each of its properties acting like a signal. For example, 'isLoading' can be accessed as xxxQuery.isLoading() or xxxQuery().isLoading(). The first case offers a more fine-grained change detection.

// Use query without params or options
postsQuery = useGetPostsQuery();

// Use query with signals params or options (can be mixed with static)
postQuery = useGetPostsQuery(myArgSignal, myOptionsSignal);

// Use query with function (similar to a computed), detect changes in the function (can be mixed)
postQuery = useGetPostsQuery(
  () => id(),
  () => ({ skip: id() <= 5 }),
);

// Use query with static params or options (can be mixed)
postQuery = useGetPostsQuery(2, {
  selectFromResult: ({ data: post, isLoading }) => ({ post, isLoading }),
});

A good use case is to work with router inputs.

// ...
<span>{{ locationQuery.isLoading() }}</span>
<span>{{ locationQuery.data() }}</span>
// ...

export class CharacterCardComponent {
  characterParamId = input.required<number>();
  characterQuery = useGetCharacterQuery(this.characterParamId);

// ...

Another good use case is with signals inputs not required and use skipToken

// ...
<span>{{ locationQuery.data() }}</span>
// ...

export class CharacterCardComponent implements OnInit {
  character = input<Character | undefined>(undefined);
  locationQuery = useGetLocationQuery(() => this.character()?.currentLocation ?? skipToken);

// ...

Lazy Queries

The use of lazy queries is a bit different compared to the original. As in the case of queries, the parameters and options of the Query can be signal or static. You can look at lazy feature example from this repository.

Like in the original library, a lazy query returns a object (not array) with each of its properties acting like a signal.

// Use query without options
postsQuery = useLazyGetPostsQuery();
// Use query with signal options
options = signal(...);
postQuery = useLazyGetPostsQuery(options);
// Use query with static options
postQuery = useLazyGetPostsQuery({
  selectFromResult: ({ data: post, isLoading }) => ({ post, isLoading }),
});

Use when data needs to be loaded on demand

//...
<span>{{ xxxQuery.data() }}</span>
<span>{{ xxxQuery.lastArg() }}</span>
//...

export class XxxComponent {
  xxxQuery = useLazyGetXxxQuery();

// ...
  xxx(id: string) {
    this.xxxQuery(id).unwrap();
  }
// ...

Another use case is to work with nested or relational data.

[!TIP] We advise using 'query' instead of 'lazy query' for these cases for more declarative code.

<span>{{ locationQuery.data() }}</span>

export class CharacterCardComponent implements OnInit {
  character = input.required<Character>();
  locationQuery = useLazyGetLocationQuery();

  ngOnInit(): void {
    this.locationQuery(this.character().currentLocation, { preferCacheValue: true });
  }

// ...

preferCacheValue is false by default. When true, if the request exists in cache, it will not be dispatched again. Perfect for ngOnInit cases. You can look at pagination feature example from this repository.

Mutations

The use of mutations is a bit different compared to the original Mutations - RTK Query guide. You can look at the examples from this repository.

Like in the original library, a mutation is a object (not array) with each of its properties acting like a signal.

// Use mutation hook
addPost = useAddPostMutation();

// Mutation trigger
this.addPost({ params });

// Can unwrap the mutation to do a action

this.addPost({ params })
  .unwrap()
  .then((data) => {
    // Do something with data
  })
  .catch((error) => {
    // Do something with error
  });

// Or

try {
  const data = await this.addPost({ params }).unwrap();
  // Do something with data
} catch (error) {
  // Do something with error
}

// Signal with the state of mutation to use in the template or component (isLoading, data, error, isSuccess, etc)
addPost.isLoading();
addPost.data();

Code-splitted/Lazy feature/Lazy modules

Important: Only for cases with differents base API url. With same base API url, it's preferable to use code splitting

To introduce a lazy/feature/code-splitted query, you must export it through an angular mule. Import this module where needed. You can look at posts feature example from this repository.

// ...
export const postsApi = createApi({
  reducerPath: 'postsApi',
  baseQuery: baseQueryWithRetry,
  tagTypes: ['Posts'],
  endpoints: (build) => ({
    // ...
  }),
});
// ...

import { provideStoreApi } from 'ngrx-rtk-query';

// ...
  providers: [
    // ...
    provideStoreApi(postsApi),
    // ...
  ],
// ...

FAQ

Contributors ✨

Thanks goes to these wonderful people (emoji key):

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