Appwrite event subscription in React Native

139 Views Asked by At

When I subscribe to realtime events in my React Native application. I get the error below.

ERROR Error: URLSearchParams.set is not implemented, js engine: hermes.

appwriteClient
      .subscribe(
 `databases.${APPWRITE_DATABASE_ID}.collections.${APPWRITE_OPPORTUNITIES_COLLECTION_ID}.documents`,
        (response: any) => {
          if (response.events.includes(
            'databases.*.collections.*.documents.*.create'
          )) {
            setOpportunities((prevOpportunities: any[]) => {
              const updatedOpportunity = [...prevOpportunities, ...response.payload];
              return updatedOpportunity;
            })
          } else if (response.events.includes(
            'database.*.collections.*.documents.delete'
          )) {
            setOpportunities((prevOpportunities: any[]) => {
              return prevOpportunities.filter((opportunity) => {
                return opportunity.$id !== response.payload.$id
              })
            })
          }
        })

I want to listen to the changes in the opportunity collection so that when changes reflect update, create, I immediately update my state.

How best can I handle appwrite event subscription in order to overcome the URLSearchParams error.

2

There are 2 best solutions below

0
On

Sometimes React Native doesn't include some things that's usually in a regular web context. The usual solution is to add a polyfill. Perhaps you can use core-js as mentioned here.

Import this early in your app (index.ts or App.tsx)

import 'core-js/actual/url';
import 'core-js/actual/url-search-params';

Another suggestion is to try react-native-url-polyfill, importing it at the root of your React Native project:

import 'react-native-url-polyfill/auto';
2
On

To handle Appwrite event subscriptions in React Native, you'll typically utilize the WebSocket SDK provided by Appwrite. Here's an example of how you might set up event subscriptions:

First, ensure you've installed the Appwrite JavaScript SDK in your React Native project:

 npm install appwrite

Then, you can create a WebSocket connection to subscribe to events in your React Native application:

import React, { useEffect } from 'react';
import { Client } from 'appwrite';

const App = () => {
  useEffect(() => {
    const client = new Client(); // Initialize your Appwrite Client

    // Replace 'YOUR_ENDPOINT' and 'YOUR_PROJECT_ID' with your actual Appwrite details
    client
      .setEndpoint('YOUR_ENDPOINT') // Your Appwrite endpoint
      .setProject('YOUR_PROJECT_ID'); // Your Appwrite project ID

    // Create a WebSocket connection
    const socket = new WebSocket(client.subscribe(['events']));

    // Listen for WebSocket connection open
    socket.onopen = () => {
      console.log('WebSocket connection established.');
    };

    // Listen for WebSocket messages
    socket.onmessage = event => {
      const eventData = JSON.parse(event.data);
      console.log('Received event:', eventData);
      // Handle the received event data here
    };

    // Handle WebSocket errors
    socket.onerror = error => {
      console.error('WebSocket error:', error);
    };

    // Clean up WebSocket connection on component unmount
    return () => {
      socket.close();
    };
  }, []); // Run this effect only once on component mount

  return (
    // Your React Native UI components
    // ...
  );
};

export default App;

This example sets up a basic WebSocket connection using the Appwrite JavaScript SDK in a React Native functional component. Replace 'YOUR_ENDPOINT' and 'YOUR_PROJECT_ID' with your actual Appwrite API endpoint and project ID, respectively.

This code establishes a WebSocket connection to subscribe to the 'events' channel. You can modify the channel name or add multiple channels to subscribe to different events.

Handle the received event data inside the socket.onmessage callback according to your application's requirements.