简体   繁体   中英

How do I call firebase functions from within a react component

I'm trying to work out how to call firebase functions from within a react component.

React component...

import React from 'react';
import './App.css';
import functions from '../functions/index'

function App() {

    const callFirebaseFunction = event =>{
        var output = functions.returnMessage()
        console.log(output)
    }

    return(
        <div>
            <button onClick={event => callFirebaseFunction()}>call function button</button>
        </div>    
    )

firebase functions index.js...

const functions = require('firebase-functions');

exports.returnMessage = functions.https.onCall((data, context) => {
    return {
        output: "the firebase function has been run"
      }
});

Hopefully my code explains what i'm trying to do. Feel free to correct any other mistakes that i'm making in this very simple example.

The issue that i'm having is that I can't import anything to the component that isn't within the src folder and the firebase functions falls outside of this. I don't really want to eject anything as i'm assuming that there is a proper way for me to access my firebase functions and I simply can't find it.

Per the documentation you need to use the firebase library in the client side to make the call to the callable function. You shouldn't be importing the server-side functions code, that needs to be deployed to firebase functions on its own -- it is not reused in the client side of the app.

Assuming you have properly imported the firebase client SDK into your client code , this means we can modify callFirebaseFunction like so:

const callFirebaseFunction = event => {
    const callableReturnMessage = firebase.functions().httpsCallable('returnMessage');

    callableReturnMessage().then((result) => {
      console.log(result.data.output);
    }).catch((error) => {
      console.log(`error: ${JSON.stringify(error)}`);
    });
}

I just updated the firebase from ^4.8.0 to ^7.21.0

And now i am able to use httpsCallable

With the release of the modern Firebase SDK, the documentation linked in the accepted answer has been updated. This means the code should now be:

import { getFunctions, httpsCallable } from "firebase/functions";

const callFirebaseFunction = event => {
    const functions = getFunctions();
    const callableReturnMessage = httpsCallable(functions, 'returnMessage');

    callableReturnMessage().then((result) => {
      console.log(result.data.output);
    }).catch((error) => {
      console.log(`error: ${JSON.stringify(error)}`);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM