Managing WebSockets with Redux Toolkit Query and TypeScript

React

We’ve learned how to use Redux Middleware to manage WebSockets in a recent article. We’ve also got to know the Redux Toolkit Query and how it can improve our code. Interestingly, we can also use RTK Query to deal with a WebSocket connection. This article teaches how to establish a WebSocket connection with RTK Query and receive and send updates.

We model the examples after both the official documentation and code written by Lenz Webber, a RTK Query contributor.

The cache lifecycle

The first feature of RTK Query that we need to get familiar with is the function. Redux Toolkit calls it when it adds a new entry to the cache when our React application accesses a particular endpoint for the first time in a while.

If you want to know more about how the cache behaves, check out Introduction to Redux Toolkit Query with TypeScript.

To explain how it works, let’s expand on an example from the previous article.

The crucial part in the above code are the two promises the function provides:

  • – it resolves when the initial request from our query responds,
  • – resolves when RTK Query removes the entry in the cache. It happens if no component uses it during the last 60 seconds by default.

To sum it up, RTK calls the function when our application requests a given endpoint for the first time, or quite some time has passed since any of our components used it. It provides us with promises that we can use to take advantage of the cache lifecycle.

Connecting to a WebSocket using React Toolkit Query

In API with NestJS #26. Real-time chat with WebSockets, we’ve created a backend application with a chat that uses socket.io. First, let’s create an enum containing all possible events.

One possible approach is to call an endpoint returning all chat messages sent in the past. Then, we can use the function to establish a WebSocket connection.

Redux Toolkit Query provides the function that we can use to modify the cache. It uses the immer library under the hood. We can safely update the object and produce the next immutable state.

Above, we add the mutation, because our API needs authentication. This is also why we add in the configuration of the .

In the API we’re dealing with, the endpoint does not exist. Instead of using it, we can emit the event and listen to the response in the  event.

Because of the above, we can use the function instead and ignore the .

Cleaning up the connection

It is worth cleaning up after listening to a stream after Redux Toolkit Query removes the cache entry. With socket.io, we can do that using the function.

Sending chat messages with Redux Toolkit Query

The official documentation does not have an example of sending messages using WebSockets. To do that with Redux Toolkit Query, we need a way to share the WebSocket connection across different endpoints.

To do that, we can look at the example written by Lenz Webber. Since we use cookie-based authentication in our WebSocket API, we should not connect immediately. Instead, let’s create a function that returns the socket.

Our API sends an acknowledgment when it receives a message. Thanks to that, our mutation can return a promise that resolves when our API recognizes the message we’ve sent.

The last step is to use the above function in our query and the mutation.

In our API, the backend sends back our new message to all of the chat users through the event. Thanks to that, we don’t need to invalidate the cache after sending a message. If your API works in a different way and you want to invalidate the cache, check out Introduction to Redux Toolkit Query with TypeScript.

Because our mutation responds with a promise, we can use the property to know that a chat message is yet to be processed by our API.

Summary

In this article, we’ve figured out a way to use Redux Toolkit Query to listen to chat messages and send them. To do that, we’ve taken examples both from the documentation and from the Redux Toolkit Query contributor. To do that, we’ve also grasped the idea of how to use the cache lifecycle to our advantage. Doing all of the above increased our knowledge of the Redux Toolkit Query.

Subscribe
Notify of
guest
7 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Christian
Christian
2 years ago

I’ve been creating a project using RTK Query + Websockets and this post helped me a lot. I was able to implement everything I wanted using the official docs and this post. Thanks!

OLEKSANDR DANYLCHENKO
OLEKSANDR DANYLCHENKO
2 years ago

Thanks! Didn’t want to create a separate POST endpoint for the data as I already have a WS connection. This post helped me to understand how to emit events from the client-side

Julian
2 years ago

I’m attempting use RTK Query together with Firestore’s real-time updates. This post should be helpful, thanks!

Saifullah Rahman
Saifullah Rahman
1 year ago

Thanks a lot

Emanuell
Emanuell
1 year ago

where can we find the source code for this tutorial?

Jonathan
Jonathan
1 year ago

Is there any way we can write unit test cases with jest for the same

dieriba
dieriba
1 year ago

I was wondering how to deal with socket connection lose when page is refreshed ?