Skip to main content

RTK Query Examples

Examples Overview

We have a variety of examples that demonstrate various aspects of using RTK Query.

These examples are not meant to be what you base your application on, but exist to show very specific behaviors that you may not actually want or need in your application. For most users, the basic examples in the Queries and Mutations sections will cover the majority of your needs.

info

The examples were created as part of the standalone @rtk-incubator/rtk-query development cycle. We're currently working to update them as part of the process of finalizing RTK Query's integration into Redux Toolkit, so some of the imports are mismatched and not all the examples are currently in the RTK repo. However, you should be able to inspect these examples and use the logic they show as guidelines.

tip

Please note that when playing with the examples in CodeSandbox that you can experience quirky behavior, especially if you fork them and start editing files. Hot reloading, CSB service workers and msw sometimes have trouble getting on the right page -- when that happens, just refresh in the CSB browser pane.

React Hooks

React Optimistic Updates

In the example below you'll notice a few things. There are two Posts list on the sidebar. The top one will only update after a successful mutation and resync with the server. The subscribed one will update immediately due to the optimistic update. In the event of an error, you'll see this get rolled back.

info

The example has some intentionally wonky behavior... when editing the name of a post, there is a decent chance you'll get a random error.

React with GraphQL

Authentication

There are several ways to handle authentication with RTK Query. This is a very basic example of taking a JWT from a login mutation, then setting that in our store. We then use prepareHeaders to inject the authentication headers into every subsequent request.

Dispatching an action to set the user state

This example dispatches a setCredentials action to store the user and token information.

Using extraReducers

This example uses a matcher from the endpoint and extraReducers in the authSlice.

React Class Components

Check out the PostDetail component for an example of Class Component usage.

Svelte