To load Firebase and make calls to, say, the database is a little more cumbersome than setting up a regular ReactJS app for example.
This is how I did it...
I created a file called firebase.js
under Assets. It looks like this
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.21.0/firebase-app.js";
import {
getDatabase,
ref,
onValue,
} from "https://www.gstatic.com/firebasejs/9.21.0/firebase-database.js";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "apiKey",
authDomain: "authDomain.firebaseapp.com",
databaseURL: "https://databaseURL.firebaseio.com",
projectId: "projectId",
storageBucket: "storageBucket.appspot.com",
messagingSenderId: "messagingSenderId",
appId: "appId",
};
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
// get data in the RTDB at a particular path
window.getData = async (path) => {
return new Promise((resolve, reject) => {
const dataRef = ref(database, path);
onValue(dataRef, (snapshot) => {
const data = snapshot.val();
resolve(data);
});
});
};
You'll see I created a function to fetch data from the Realtime Database called getData
. In order to access it from other pages in the Shopify theme, I need to attach it to the window
object.
Then in the header of theme.liquid
file, I added
<script type="module" src="{{ 'firebase.js' | asset_url }}"></script>
Setting the type to module is needed as I'm using import statements in the firebase.js
file.
Let's say we want to reference this file from a section file in Shopify. I added the following code to that section file...
<script type="text/javascript">
window.addEventListener('load', async ()=> {
const artists = await getData('artists);
console.log(artists);
});
</script>
I needed to add window.addEventListener('load', async ()=> {
to make sure the Firebase libraries load first before I can use that getData
function.