Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 719
Thomas Fox Avatar asked Feb 03 '23 16:02

Thomas Fox


1 Answers

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)}`);
    });
}

Note: Due to when this question was originally asked and the firebase version it used, this answer uses the "Web version 8 (namespaced)" method of calling style. Since then, there is also a "Web Version 9 (modular)" style (at the documentation link) that may be more appropriate. (See this answer).

like image 82
robsiemb Avatar answered Feb 08 '23 15:02

robsiemb