Firebase 10.1.0 and p5

Hello forum,

In the past I have been successful integrating a p5 sketch with a firebase realtime database. When I went to start a new project, it’s not working the way that it used to and I am stuck.

With firebase version 8, I linked to the firebase library almost the same way I link to the p5 library, with a script tag in index.html:

 <script src="https://cdn.jsdelivr.net/npm/firebase@8.10.0/firebase.js"></script> 

This doesn’t work in the latest version of firebase.

The firebase installation instruction tells me to add the script as a type = “module” and then to add these lines of code into my index.js file:

import { initializeApp } from 'https://www.gstatic.com/firebasejs/10.1.0/firebase-app.js';
import { getDatabase } from "https://www.gstatic.com/firebasejs/10.1.0/firebase-database.js";

my sketch.js file doesn’t run properly if I call it as type=module, and I can’t get my p5 code to work in index.js. If I run both index.js and sketch.js from index.html, sketch.js is not able to access the database variables defined in index.js (even though I believe they are global).

Here is the link to the full project : p5.js Web Editor
I’m adding the p5 editor link because it’s easy to see, but I’ve mainly been working on it in VScode with a local server, so I know that the error isn’t caused by an issue within the editor.

Thank you for your help!!

1 Like

Thank you! This example was super helpful and I was able to connect with firebase.

I continue to struggle with the syntax since the firebase ref() method used to work but doesn’t now. I think that maybe I am missing a step.
Uncaught TypeError: Cannot read properties of undefined (reading ‘ref’) at _main.default.Element.submitName

my code with ref:

 var r = database.ref('name');

vs ref method in firebase reference:

export declare function ref(db: Database, path?: string): DatabaseReference;

Here is a link to my full code in p5 editor and also to the reference.

I am grateful for any help in understanding this syntax. Thank you so much!

Warning: I’ve never used Firebase! :warning:

That’s a call signature for function ref()'s parameter datatypes and what datatype ref() returns.

Its 1st parameter db is of datatype Database, not a string!

Most likely you should instead pass your variable database, which was initialized w/ the Database object returned by calling function getDatabase().

Running your code the error message I get after clicking at button “submit” is this 1:
Uncaught TypeError: database.ref is not a function

And if I log it I get undefined:
console.log(database.ref);

If we scroll up we’ll see function ref() belongs to package module “database”:
https://Firebase.Google.com/docs/reference/js/database.md#database_package

So you’re gonna need to import it alongside function getDatabase(), which also belongs to that module as well:
import { getDatabase, ref } from "blah-blah-blah.js"
globalThis.ref = ref;

2 Likes