Blog>
Snippets

Using RTK Query with Cache Invalidation

Demonstrate how to use the enhanced caching and invalidation features of RTK Query in Redux Toolkit 2.0 to perform automatic refetching of data.
// Define an API service using createApi
const api = createApi({
    baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
    tagTypes: ['Posts'],
    endpoints: (builder) => ({
        getPosts: builder.query({
            query: () => '/posts',
            providesTags: ['Posts']
        }),
        addPost: builder.mutation({
            query: (newPost) => ({
                url: '/posts',
                method: 'POST',
                body: newPost
            }),
            invalidatesTags: ['Posts']
        })
    }),
    // Configure cache invalidation behavior
    invalidationBehavior: 'delayed'
});

// Export hooks for usage in functional components
export const { useGetPostsQuery, useAddPostMutation } = api;
Creates an API service with getPosts query and addPost mutation, sets up cache invalidation behavior to 'delayed', and exports hooks.