I'm following the Net Ninja's tutorial about firebase cloud functions and I can't figure out how to call a function from a vue component. (he doesn't use vue in the tutorial).
So I have this vue3 app with firebase functions installed in it. How do I import the functions into a component? I can't find the answer anywhere. I'm still learning to code and I still don't understand very well how to import the packages needed.
I have a index.js file in the functions folder with a few functions inside. I now want to call one of them ( a .onCall function) when clicking a button in a component.
I understand I need to import something in that component but I can't figure out what!
Your Vue.js app and your Cloud Functions for Firebase are totally different components of your whole application.
The Vue.js app is a front-end component (even if it is hosted in a cloud service like Firebase Hosting).
The Cloud Functions are serveless back-end components, hosted in the Firebase (Google Cloud) infrastructure and reacting to events.
To get these two components interacting with each other there are basically two possibilities:
How do I import the functions into a component?
As explained above, you cannot integrate a Cloud Function code in your Vue.js code. In particular you cannot "import the functions into a component".
I now want to call one of them (a .
onCall()function) when clicking a button in a component.
If your Cloud Function is a Callable one, you can call it through the JS SDK as explained in the documentation.
UPDATE Following your comment:
As explained in the documentation, to call the Callable Function from your Vue.js app, you need to do as folloows (with the JS SDK v9):
Add Firebase to your Vue.js app. For example via a firebaseConfig.js file:
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getFunctions } from "firebase/functions";
const firebaseConfig = {
apiKey: "...",
// ....
};
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
const functions = getFunctions(firebaseApp);
export { db, functions };
Then, in your component, you do
<script>
import { functions } from '../firebaseConfig';
import { httpsCallable } from 'firebase/functions';
// ...
methods: {
async callFunction() {
const addMessage = httpsCallable(functions, 'addMessage');
const result = await addMessage({ text: messageText })
const data = result.data;
//...
});
}
</script>