Search code examples
javascriptfirebasereact-nativegoogle-cloud-functionsreact-native-firebase

Firebase Cloud function in expo project


So I have a cloud function (this is not in the react native app directory yet):

const admin = require('firebase-admin');
const firebase_tools = require('firebase-tools');
const functions = require('firebase-functions');

admin.initializeApp();


exports.deleteUser = functions
  .runWith({
    timeoutSeconds: 540,
    memory: '2GB'
  })
  .https.onCall((data, context) => {

  const userId = context.auth.uid;
  var promises = [];

  // DELETE DATA
  var paths = ['users/' + userId, 'messages/' + userId, 'chat/' + userId];

  paths.forEach((path) => {
    promises.push(
      recursiveDelete(path).then(  () => {
          return 'success';
        }
      ).catch( (error) => {
        console.log('Error deleting user data: ', error);
      })
    );
  });

  // DELETE FILES
  const bucket = admin.storage().bucket();
  var image_paths = ["avatar/" + userId, "avatar2/" + userId, "avatar3/" + userId];
  image_paths.forEach((path) => {
    promises.push(
      bucket.file(path).delete().then(  () => {
            return 'success';
          }
        ).catch( (error) => {
          console.log('Error deleting user data: ', error);
        })
      );
    });

  // DELETE USER
  promises.push(
    admin.auth().deleteUser(userId)
    .then( () => {
      console.log('Successfully deleted user');
      return true;
    })
    .catch((error) => {
      console.log('Error deleting user:', error);
    })
  );

  return Promise.all(promises).then(() => {
    return true;
  }).catch(er => {
      console.error('...', er);
  });
});




function recursiveDelete(path, context) {
    return firebase_tools.firestore
    .delete(path, {
      project: process.env.GCLOUD_PROJECT,
      recursive: true,
      yes: true,
      token: functions.config().fb.token
    })
    .then(() => {

      return {
        path: path
      }
    }).catch( (error) => {
      console.log('error: ', error);
      return error;
    });
  }
  // [END recursive_delete_function]

This is used for my swift app. How Can I use this for my react native app built with Expo?

I have installed the following yarn add @react-native-firebase/functions

I have my firebase.js file set up in the root directory:

import * as firebase from "firebase";

// Your web app's Firebase configuration
var firebaseConfig = {
    apiKey: "test",
    authDomain: "test",
    databaseURL: "test",
    projectId: "test",
    storageBucket: "test",
    messagingSenderId: "test",
    appId: "test"
  };

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

export default firebase;

I have a button:

<Text>Delete Account</Text>
<View>
    <Button
        title="Delete Account"
        color="#F9578E"
        accessibilityLabel="Delete Account"
    />
</View>

Which when clicked signs the user out and runs the above cloud function.


Solution

  • I'm not versed in react-native and in Expo, but from the @react-native-firebase/functions documentation it seems that you need to do as follows:

    import functions from '@react-native-firebase/functions';
    
    function App() {
    
    
      useEffect(() => {
        functions()
          .httpsCallable('deleteUser')()
          .then(response => {
            // ....
          });
      }, []);
        
      // ...
    }
    

    You are not passing any data from your app to your Callable Cloud Function, i.e. you are not using the data object in your Cloud Function, this is why you need to do functions().httpsCallable('deleteUser')(). If you would need to pass some data, the doc shows an example here, passing an object:

    functions().httpsCallable('listProducts')({
      page: 1,
      limit: 15,
    })
    

    (This is totally in line with the Firebase JS SDK way of calling a Callable Cloud Function, this is why I answered to the question, even with a lack of knowledge on react-native and on Expo...)