react-native-cloud-storage

repository·main·Indexed 42 days ago

https://github.com/kuatsu/react-native-cloud-storage

A unified API for accessing cloud storage services like iCloud and Google Drive in React Native applications. It supports file-based storage and key-value stores across iOS, Android, and Web, providing tools such as the CloudStorage imperative API, CloudKVStorage for AsyncStorage-style management, and the useCloudKV hook for reactive state.

Tokens
21.2K
Snippets
75
Records
85
Agent score
54%

What's inside react-native-cloud-storage

  1. Introduction to React Native Cloud Storage

    main

    React Native Cloud Storage provides a developer-friendly API for using iCloud (iOS only) and Google Drive as file and data storage in React Native applications. The API is modeled after Node's fs and AsyncStorage to minimize the learning curve.

    Core Capabilities

    • File Storage: Use an fs-like API including readFile, writeFile, appendFile, readdir, mkdir, stat, and unlink.
    • Key-Value Storage: Save preferences and small app states using native iCloud key-value storage or an emulated Google Drive store.
    • Unified API: Use the same methods regardless of the provider (iCloud or Google Drive).
    • Scopes: Choose between AppData (hidden, app-private container) or Documents (user-visible folder).
    • React Hooks: Access reactive values for files, key-value state, and provider availability using useCloudFile, useCloudKV, and useIsCloudAvailable.
    • Modern Architecture: Built as a Turbo Module and fully typed with TypeScript.
  2. React to external changes from other devices

    main

    You can listen for changes made to the cloud store from other devices using subscribeToExternalChanges.

    • iCloud: Uses native push events.
    • Google Drive: Does not support push. Instead, you must enable polling by setting kvPollInterval in setProviderOptions. Polling starts when the first listener subscribes and stops when the last one unsubscribes.

    If changedKeys is empty, it indicates a general change (like an iCloud account change) and you should refresh all relevant values.

    import { CloudKVStorage } from 'react-native-cloud-storage';
    
    // Enable polling for Google Drive
    CloudKVStorage.setProviderOptions({ kvPollInterval: 15_000 });
    
    const handleChange = async (event: { changedKeys: string[] }) => {
      if (event.changedKeys.length === 0 || event.changedKeys.includes('theme')) {
        console.log('New theme:', await CloudKVStorage.getItem('theme'));
      }
    };
    
    CloudKVStorage.subscribeToExternalChanges(handleChange);
    
    // To stop listening:
    // CloudKVStorage.unsubscribeFromExternalChanges(handleChange);
  3. Quick Start with react-native-cloud-storage

    main

    This example demonstrates how to check for cloud availability using the useIsCloudAvailable hook, configure Google Drive with an access token, and perform basic file operations using the CloudStorage imperative API.

    Note: For Google Drive, you must obtain an access token using a library like @react-native-google-signin/google-signin before calling CloudStorage.setProviderOptions.

    import React from 'react';
    import { Platform, View, Text, Button } from 'react-native';
    import { CloudStorage, CloudStorageProvider, useIsCloudAvailable } from 'react-native-cloud-storage';
    
    const App = () => {
      const cloudAvailable = useIsCloudAvailable();
    
      React.useEffect(() => {
        if (CloudStorage.getProvider() === CloudStorageProvider.GoogleDrive) {
          // get access token via @react-native-google-signin/google-signin or similar
          CloudStorage.setProviderOptions({ accessToken: 'some-access-token' });
        }
      }, []);
    
      const writeToCloud = async () => {
        await CloudStorage.writeFile('/file.txt', 'Hello, world!');
        console.log('Successfully wrote file to cloud');
      };
    
      const readFromCloud = async () => {
        const value = await CloudStorage.readFile('/file.txt');
        console.log('Successfully read file from cloud:', value);
      };
    
      return (
        <View>
          {cloudAvailable ? (
            <>
              <Button onPress={writeToCloud} title="Write to Cloud" />
              <Button onPress={readFromCloud} title="Read from Cloud" />
            </>
          ) : (
            <Text>The cloud storage is not available. Are you logged in?</Text>
          )}
        </View>
      );
    };
  4. Develop the documentation site

    main

    To run the documentation site in development mode, it is preferred to run the command from the repository root to ensure workspace dependencies resolve correctly. Running the development command will automatically regenerate the API reference from the library's TSDoc before starting the dev server.

    pnpm --filter react-native-cloud-storage-docs dev
  5. Set up the Android example project

    main

    Running the Android example requires a valid Google Drive API access token.

    1. Generate Token: Use the Google OAuth 2.0 Playground to create a token.
    2. Select Scopes: From the "Drive API v3" list, select one or both of the following scopes:
      • https://www.googleapis.com/auth/drive (required if using CloudStorageScope.Documents)
      • https://www.googleapis.com/auth/drive.appdata
    3. Exchange Code: Generate an authorization code and exchange it for an access token.
    4. Input Token: If using an emulator, you can quickly input the token using adb shell input text. Ensure the text input field in the emulator is focused before running the command.
    abd shell input text '{some_token}'
  6. Use multiple CloudStorage providers simultaneously

    main

    To use multiple providers (e.g., backing up to both iCloud and Google Drive at the same time), do not rely on the static default instance. Instead, instantiate new CloudStorage objects by passing the desired CloudStorageProvider to the constructor.

    Note: When instantiating a provider that is not native to the current platform (e.g., using CloudStorageProvider.ICloud on Android), the operation will throw an error.

    import { CloudStorageProvider, CloudStorage } from 'react-native-cloud-storage';
    
    // Create specific instances for different providers
    const iCloudStorage = new CloudStorage(CloudStorageProvider.ICloud);
    const googleDriveStorage = new CloudStorage(CloudStorageProvider.GoogleDrive, { accessToken: 'some_access_token' });
    
    // Use the instances independently
    await iCloudStorage.writeFile('/test.txt', 'Hello, iCloud!');
    await googleDriveStorage.writeFile('/test.txt', 'Hello, Google Drive!');
  7. Set up the iOS example project

    main

    To run the iOS example, you must configure a valid Apple App ID and iCloud container.

    1. Configure Bundle Identifier: In apps/example/app.json, set expo.ios.bundleIdentifier to an App ID owned by your Apple team.
    2. iCloud Container: By default, the react-native-cloud-storage plugin uses iCloud.<bundleIdentifier> as the container identifier. If you need a custom container, specify iCloudContainerIdentifier in the plugin's options.
    3. Provisioning: Ensure you register the App ID and container for your team and use a provisioning profile that supports them.
    4. Build and Run: From the repository root, build the package and launch the iOS example.

    Refer to the Expo installation guides and iCloud setup checks for detailed signing and device configuration requirements.

    pnpm package build
    pnpm example ios
  8. Install react-native-cloud-storage in an Expo Managed project

    main

    To use react-native-cloud-storage in an Expo Managed project, follow these steps:

    1. Install the package using your preferred package manager:

      npm install react-native-cloud-storage
      # or
      yarn add react-native-cloud-storage
    2. Configure the Expo Config Plugin: Since the library contains native code, you must add it to the plugins array in your app.json to automate native project modifications.

    3. Use a Development Client: This library is not compatible with Expo Go. You must create and use a development build to run the application.

    4. Architecture Requirement: Newer versions of this library require the React Native New Architecture. If you are using the Legacy Architecture, you must either migrate to the New Architecture or install version 2 of the library using npm install react-native-cloud-storage@^2.

    npm install react-native-cloud-storage
  9. Install react-native-cloud-storage in a bare React Native project

    main

    To install react-native-cloud-storage in a bare React Native project, first install the package via your package manager.

    Architecture Compatibility Note:

    • New Architecture: Use the latest version of the library.
    • Legacy Architecture: If you cannot migrate to the New Architecture, you must use version 2 by installing react-native-cloud-storage@^2.

    After installing the package, install the native iOS pods using autolinking:

    npm install react-native-cloud-storage
    cd ios && pod install && cd ..
  10. Configure iCloud capability for iOS

    main

    After installing the library and pods, you must configure the iCloud capability in Xcode to allow document access:

    1. Open your Xcode workspace.
    2. Select your main project target and navigate to the Signing & Capabilities tab.
    3. Click the + Capability button and add iCloud.
    4. In the iCloud section, under Services, enable iCloud Documents.
    5. Create a new container named iCloud.{bundle_identifier}, replacing {bundle_identifier} with your project's actual bundle identifier.

    If you are using CloudKVStorage, you must also enable Key-value storage in the iCloud capability section. Ensure your target includes the following entitlement:

    com.apple.developer.ubiquity-kvstore-identifier

    Warning: Your Apple App ID and provisioning profile must support iCloud key-value storage. If the entitlement is missing, local operations might work, but data will not synchronize across devices.