Blog>
Snippets

Sending Messages through WebSockets using React Query

Demonstrate the use of React Query's useMutation hook to send data through a WebSocket connection.
import { useMutation } from '@tanstack/react-query';
import { useContext } from 'react';
import { WebSocketContext } from './WebSocketProvider';
Imports the useMutation hook from React Query, useContext hook from React, and the WebSocketContext created to manage WebSocket connections.
const sendMessageMutation = useMutation(
  message => {
    const { sendMessage } = useContext(WebSocketContext);
    return new Promise((resolve, reject) => {
      if (sendMessage) {
        sendMessage(message);
        resolve('Message sent successfully');
      } else {
        reject('Connection not established');
      }
    });
  }
);
Sets up a mutation using useMutation to send a message through WebSocket. It utilizes the sendMessage function from WebSocketContext. If the connection is not established, it rejects the promise.
const handleSend = () => {
  const message = 'Hello world';
  sendMessageMutation.mutate(message, {
    onSuccess: () => console.log('Message sent'),
    onError: error => console.error('Error sending message:', error)
  });
};
A function to handle sending messages. It calls sendMessageMutation.mutate with the message and handles success or errors.