RTK Query

RTK Query is Redux Toolkit's powerful data fetching and caching layer. It eliminates the need to write async action creators and manages loading states, caching, and data synchronization automatically.

Base Client Configuration

All RTK Query endpoints extend from a single base client instance.

Base Query Setup

// src/services/baseQuery.ts
import { fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import type { RootState } from '@/app/store';

export const baseQuery = fetchBaseQuery({
  baseUrl: process.env.NEXT_PUBLIC_API_URL, // e.g., https://api.decentraland.org
  
  prepareHeaders: (headers, { getState }) => {
    const state = getState() as RootState;
    
    // Add authentication token
    const token = state.user.session?.authToken;
    if (token) {
      headers.set('authorization', `Bearer ${token}`);
    }
    
    // Add chain ID for web3 context
    const chainId = state.user.chainId;
    if (chainId) {
      headers.set('x-chain-id', String(chainId));
    }
    
    // Standard headers
    headers.set('accept', 'application/json');
    headers.set('content-type', 'application/json');
    
    return headers;
  },
  
  credentials: 'omit', // or 'include' if backend requires cookies
});

Client Instance

Tag Conventions

Tags are used for cache invalidation and synchronization. Follow these conventions:

Tag Naming

Resource Type
Query Tags
Mutation Invalidates

Collections

'Parcels' (plural)

'Parcels'

Single Entity

{type: 'Parcels', id: '123'}

{type: 'Parcels', id: '123'}

List + Detail

['Parcels', {type: 'Parcels', id}]

['Parcels'] or specific id

Tag Examples

Creating Endpoints

Endpoints SHOULD be co-located with their feature in feature.client.ts files.

Query Endpoint (Read)

Mutation Endpoint (Write)

Optimistic Updates

Use onQueryStarted for optimistic UI updates with automatic rollback on failure.

Advanced Query Options

Polling

Skip Query

Lazy Query

Transform Response

Custom Serialization

For pagination or search, customize cache key serialization:

Error Handling

Custom Error Handling

Usage in components:

Cache Management

Manual Cache Updates

Invalidate Cache

Reset Client State

Prefetch Data

Best Practices

1. Use Descriptive Endpoint Names

2. Provide Comprehensive Tags

3. Handle Loading and Error States

4. Use Type Guards

Next Steps

Last updated