Appwrite React Native SDK

repository·main·Indexed 26 days ago

https://github.com/appwrite/sdk-for-react-native

The react-native-appwrite SDK (v0.34.0) integrates React Native applications with the Appwrite backend-as-a-service. It provides access to authentication, databases, and storage, featuring support for OAuth2 sessions, MFA (TOTP), anonymous sessions, and JWT generation. The SDK includes TypeScript generics for type-safe database operations and requires react-native-url-polyfill for environment compatibility.

Tokens
49.7K
Snippets
133
Records
225
Agent score
85%

What's inside react-native-appwrite

  1. Configure Appwrite Platforms for iOS and Android

    main

    Before using the SDK, you must add your application as a platform in your Appwrite project settings.

    iOS

    Add your app name and Bundle ID.

    • In Xcode: Find the Bundle Identifier in the General tab of your primary target.
    • In Expo: Set or find it in your app.json file.

    Android

    Add your app name and package name.

    • In standard Android: The package name is typically the applicationId in your app-level build.gradle file.
    • In Expo: Set or find it in your app.json file.
  2. Initialize the Appwrite Client

    main

    To use the SDK, you must first import the polyfill in your index.js and then initialize the Client with your Appwrite endpoint, project ID, and platform ID (Bundle ID for iOS or Package Name for Android).

    import 'react-native-url-polyfill/auto';
    import { Client } from 'react-native-appwrite';
    
    // Init your React Native SDK
    const client = new Client();
    
    client
        .setEndpoint('http://localhost/v1') // Your Appwrite Endpoint
        .setProject('455x34dfkj') // Your project ID
        .setPlatform('com.example.myappwriteapp') // Your application ID or bundle ID
    ;
  3. Handle Appwrite Errors

    main

    The SDK throws AppwriteException objects when requests fail. These objects contain the following properties:

    • message: A human-readable error message.
    • code: The error code.
    • response: The full response object.
    try {
        const user = await account.create(ID.unique(), "email@example.com", "password", "Walter O'Brien");
        console.log('User created:', user);
    } catch (error) {
        // error is an AppwriteException
        console.error('Appwrite error:', error.message);
    }
  4. Query GraphQL with the Graphql class

    main

    Use the Graphql class to execute GraphQL queries against your Appwrite instance. You must first initialize a Client with your API endpoint and project ID, then pass that client instance to the Graphql constructor. The .query() method accepts an object containing a query key with your GraphQL query string.

    import { Client, Graphql } from "react-native-appwrite";
    
    const client = new Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>'); // Your project ID
    
    const graphql = new Graphql(client);
    
    const result = await graphql.query({
        query: `
          query MyQuery {
            user(id: "USER_ID") {
              name
              email
            }
          }
        `
    });
    
    console.log(result);
  5. Update account phone number with updatePhone()

    main

    Use the updatePhone method on an Account instance to update the phone number associated with the currently authenticated user. This requires providing the new phone number in E.164 format and the user's current password for verification.

    import { Client, Account } from "react-native-appwrite";
    
    const client = new Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>'); // Your project ID
    
    const account = new Account(client);
    
    const result = await account.updatePhone({
        phone: '+12065550100',
        password: 'password'
    });
    
    console.log(result);
  6. List countries and phone formats with Locale.listCountriesPhones()

    main

    Use the listCountriesPhones() method on a Locale instance to retrieve a list of countries along with their associated phone number formats. This requires an initialized Client instance.

    import { Client, Locale } from "react-native-appwrite";
    
    const client = new Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>'); // Your project ID
    
    const locale = new Locale(client);
    
    const result = await locale.listCountriesPhones();
    
    console.log(result);
  7. Create a Push Target with the Account service

    main

    Use the account.createPushTarget method to register a push notification target for a user. This requires a targetId and an identifier. You can optionally provide a providerId.

    import { Client, Account } from "react-native-appwrite";
    
    const client = new Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>'); // Your project ID
    
    const account = new Account(client);
    
    const result = await account.createPushTarget({
        targetId: '<TARGET_ID>',
        identifier: '<IDENTIFIER>',
        providerId: '<PROVIDER_ID>' // optional
    });
    
    console.log(result);
  8. Delete a team membership

    main

    Use the deleteMembership method from the Teams class to remove a specific membership from a team. This requires both the teamId and the membershipId.

    import { Client, Teams } from "react-native-appwrite";
    
    const client = new Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>'); // Your project ID
    
    const teams = new Teams(client);
    
    const result = await teams.deleteMembership({
        teamId: '<TEAM_ID>',
        membershipId: '<MEMBERSHIP_ID>'
    });
    
    console.log(result);
  9. Create a Magic URL Token with Account.createMagicURLToken

    main

    Use the createMagicURLToken method from the Account class to generate a magic URL token for passwordless authentication. This token allows a user to authenticate via a magic link sent to their email.

    Required parameters:

    • userId: The ID of the user.
    • email: The email address where the magic link will be sent.

    Optional parameters:

    • url: The URL to be included in the magic link.
    • phrase: A boolean indicating whether to use a magic phrase instead of a link (defaults to false).
    import { Client, Account } from "react-native-appwrite";
    
    const client = new Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>'); // Your project ID
    
    const account = new Account(client);
    
    const result = await account.createMagicURLToken({
        userId: '<USER_ID>',
        email: 'email@example.com',
        url: 'https://example.com', // optional
        phrase: false // optional
    });
    
    console.log(result);
  10. Create email verification with Account.createEmailVerification()

    main

    Use the createEmailVerification method on an Account instance to send an email verification link to a user. You must provide a url parameter, which is the destination URL where the user will be redirected after clicking the verification link in their email.

    To use this, you need an initialized Client and an Account instance.

    import { Client, Account } from "react-native-appwrite";
    
    const client = new Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>'); // Your project ID
    
    const account = new Account(client);
    
    const result = await account.createEmailVerification({
        url: 'https://example.com'
    });
    
    console.log(result);
  11. Retrieve a transaction using TablesDB.getTransaction()

    main

    Use the getTransaction method from the TablesDB class to fetch details for a specific transaction. You must provide a transactionId in the options object. This requires an initialized Client instance.

    import { Client, TablesDB } from "react-native-appwrite";
    
    const client = new Client()
        .setEndpoint('https://<REGION>.cloud.appwrite.io/v1') // Your API Endpoint
        .setProject('<YOUR_PROJECT_ID>'); // Your project ID
    
    const tablesDB = new TablesDB(client);
    
    const result = await tablesDB.getTransaction({
        transactionId: '<TRANSACTION_ID>'
    });
    
    console.log(result);