How can I use Firebase 9.x + Flow - javascript

I'm working on a NextJS project using Flow and I'm trying to import Firebase latest version 9.1.3, but when I try to use it, Flow complains that cannot find the module.
// Error: Cannot resolve module `firebase/app`.Flow(cannot-resolve-module)
import { initializeApp, getApps } from 'firebase/app';
import { getAnalytics } from 'firebase/analytics';
I only found an old solution on flow-typed for Firebase 5.x.x, but API has changed since then, and manually writing a Library Definition is super time consuming.
I noticed that Firebase uses Typescript, is there a way I can import/convert to use Flow?

No flow types and TS types are not compatible although they achieve the same goal they are different in their typing philosophy.
Regarding firebase types, because firebase doesn't use flow, flow-typed is the correct place to retrieve them if the existed but no one has done so for firebase types for a while.
I have personally made a start in a project I started a while back but you may need to add more to suit your usecase (firebase types in my project). If these suit your usecase as a base I'm happy to commit them into flow-typed but I'll just need to include some tests.

Related

'Firebase Not Defined' An Answer For Version 9 Of Firebase

Im trying to make a database call/post but im getting the error
functions.js:7 Uncaught ReferenceError: firebase is not defined
From my research it is my understanding that 'firebase' is defined in the firebase.js script file that is imported using the CDN code from the setting panel in Firebase..
But all the help pages i find are from 2014-2017 and version 9 of Firebase uses a completely different import language.. These pages are no help to me..
I am using the standard
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
Am I right in thinking that because this import is happening (and its seemingly is - firebase-app.js is showing up in the inspector) That firebase should be defined...
Or is firebase defined somewhere else and im missing something??
If this is the case where is firebase defined and how do i import it (with V9 Firebase)
Thanks
Edit: Im doing this all through a tutorial I found on Youtube, its from 2019.. Is it possible that calling upon 'firebase' now is outmoded and that is what I am having these troubles? Or should i expect it to work and keep trying to find a solution?
In v8 and older versions of the Firebase Web SDK, now referred to as the "namespaced SDK", the SDK would add methods and types to a global object called firebase. You will see a lot of existing tutorials with code that looks like firebase.initializeApp(), firebase.database() and firebase.firestore.FieldValue.increment(). All of these calls will not work in the newer versions of the Firebase Web SDK.
In v9 and later versions of the Firebase Web SDK, now referred to as the "modular SDK", the SDK undertook a major architectural revamp and introduced lots of breaking changes. The primary change with the new version is that the firebase global object was completely removed and every method and type is now exported independently. When using this new SDK with a build tool like Webpack or Rollup, it can "shake the tree" to loosen and remove all of the bits of code that you don't actually use in your code from the final build.
As an example, if you don't use any of the FieldValue transforms in your code (like increment(), serverTimestamp() and arrayUnion()) they won't be included in your final build saving you and your users resources and time.
Not sure how you are using the script files, but have u defined them as "modules" in you html like:
and have you initialized firebase from your app:
const firebaseConfig = {
YOU_FIREBASE_CONFIG
}
const app = initializeApp(firebaseConfig)
The difference between v8 and v9 of firebase is a well-known error these days.
I am not sure this could be the exact solution, but at least as a hint.
Using compat is a way to solve.
Based in the firebase document below.
import firebase from 'firebase/compat/app';
↑would be how to import.....
Upgrade from version 8 to the modular Web SDK
When you run this code:
import { initializeApp } from ...
This code imports only the initializeApp function, and nothing else. That's precisely its point, because by using these very granular imports, bundler tools (like webpack) are able to drop any part of the Firebase SDK that you are not using from their output, resulting in a significantly smaller app.
So when you run that import, there is no top-level firebase namespace anymore. To access the Realtime Database, you'd instead use:
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";
// Set the configuration for your app
// TODO: Replace with your project's config object
const firebaseConfig = {
apiKey: "apiKey",
authDomain: "projectId.firebaseapp.com",
databaseURL: "https://databaseName.firebaseio.com",
storageBucket: "bucket.appspot.com"
};
const app = initializeApp(firebaseConfig);
// Get a reference to the database service
const database = getDatabase(app); // 👈 Get the database instance
This is shown in the documentation on initializing the Realtime Database JavaScript SDK, so I recommend keeping that handy.
If you're following a tutorial or documentation from elsewhere, it likely hasn't been updated to the new modular syntax yet. You can also use the compat mode of the new SDK in that case, as user K Lee pointed out in their answer.
After a while I realized that all your Javascript code has to be run within the SDK module tags that you import from the Firebase Dashboard...
If your Javascript is not run within the <script type="module"> tags from the imported Firebase code the imported modules from Firebase's modular SDK wont be defined.
Also I was trying to go through a tutorial that was from V5 of Firebase and was running into problems there as well.

Flow complains about untyped import

I'm starting out on a React Native project that uses react-native-geolocation-service to get the user's GPS location, but Flow is complaining that the library is untyped. The library has Typescript types, but doesn't seem to have Flow types, and VS Code gives me this error when I import the library.
Importing from an untyped module makes it any and is not safe! Did you mean to add // #flow to the top of react-native-geolocation-service? (untyped-import)Flow(LintError-untyped-import)
Can I convince Flow to stop complaining about this library, or should I switch to Typescript? I don't have any particular preference for Flow, it's just what react-native init set up for me.
I used this to create the project:
npx react-native init WarmerWalker
Then I added the library like this:
npm install react-native-geolocation-service
I import the library like this in my App.js:
import Geolocation from 'react-native-geolocation-service';
I tried adding the library to the untyped section in .flowconfig, but that didn't help. Neither did the ignore section.
The code seems to work, it's just making Flow complain.
Thanks to a comment from Alex, I learned about strict mode. The sample app that react-native created used #flow strict-local, so that was causing the problem. Removing strict-local made it stop complaining.
However, since the library I want to use has Typescript type definitions, I'm going to switch to Typescript. I regenerated the sample app with the Typescript template, like this:
npx react-native init MyApp --template react-native-template-typescript

How to do unit testing in react native that uses firebase?

Im quite new to jest unit testing, so stuff like mocking modules is confusing.
In react native, there is a component that uses firebase databse that returns data from a given ref:
// when the data of the current user is available
userRef.child(user.uid).on('value', snap => {
// check of val() consists data
if (snap.val()) {
let
authUser = snap.val(),
isPatient = authUser.type === "Patient",
// We update the state object so that the component is re-rendered
this.setState({
// the ID of the current user
authUserUID: user.uid,
// the type of the current user (i.e. Doctor or Patient)
authUserType: snap.val().type,
// title of the dashboard based on the current user type
activeTitle: snap.val().type === "Doctor" ? "My Patients" : "My Doctors",
});
}
});
I'm now trying to do unit testing which uses this component:
import 'react-native'
import React from 'react'
import renderer from 'react-test-renderer'
import LaunchScreen from "../../App/Containers/LaunchScreen";
test('LaunchScreen', () => {
const tree = renderer.create( <LaunchScreen / > ).toJSON()
expect(tree).toMatchSnapshot()
})
But it gives a weird error
RNFirebase core module was not found natively on iOS, ensure you have correctly included the RNFirebase pod in your projects Podfile and have run pod install
I have no idea since the firebase does return data if I run it. So why is it saying that RNFirebase cannot be found?
Thanks
Update
One of the answers have given a nice step by step instructions, and although it solves partially the proposed question; the error still persists. For example; I'm now getting this new error:
console.error node_modules\react-test-renderer\cjs\react-test-renderer.development.js:5530
The above error occurred in the component:
in LaunchScreen
Consider adding an error boundary to your tree to customize error handling behavior.
TypeError: _reactNativeFirebase2.default.app is not a function
https://gist.github.com/himanshusinghs/bd86262ce3c9e6f4d691b5242de707ef
Above is the link to a gist containing the mock of React Native Firebase. Implementation instructions are also there. I am summarising them here as well -
1. You will be mocking a node_module and to do so there are multiple ways depending upon your use case. But since you will need to mock Firebase for almost every component that utilizes it, we will be implementing a global mock of React Native Firebase module.
2. Create a __mocks__ folder in your project's root directory adjacent to your node_modules folder.
3. Now create a file named react-native-firebase.js inside the __mocks__ directory.
4. Copy paste the contents from RNFirebaseMock.js in the above gist to your react-native-firebase.js file.
How this works ?
Jest has an auto mocking feature. Now every time you will run your test cases using Jest, and whenever any of your test case will require react-native-firebase module, Jest will first look into __mocks__ folder and see if there is a react-native-firebase.js containing some mock implementation of the required module.
If there is then jest will require that mock implementation instead of original module otherwise it will continue on to require original react-native-firebase module.
Things to be noted
You need to observe that the name of the mock file that we created react-native-firebase.js inside __mocks__ folder is similar to the name of installation folder of actual react-native-firebase module. Just go to node_modules and scroll down till you find react-native-firebase folder.
Yes, the name of your mock implementation of a module need to be exactly same as the name of the module itself.
Things to do this point onwards
Congratulations for you started with unit testing and chose an awesome framework for the same. Trust me, testing react-native or react is such a PITA (Pain in the Ass) that you should consider going through Jest documentation seriously and primarily focus on the mock part.
Later you may very well encounter problems while setting up Jest for react-native or react and there the documentation will come in handy.
Here are some series of tutorials and references that helped me get started with Jest and unit testing react and react-native -
Jest Documentation
Testing React and React Native using Jest/Enzyme setup
Reference article for Mocks, Stubs and Fakes
Testing Redux - P1
Testing Redux - P2
Testing Redux - P3
Solution for the error after applying RNFirebaseMock
The error that you now are getting is because there doesn't exist a function named app under default export of your mock. So let create it.
Go to your mocks directory and open react-native-firebase-mock.js. look for export default class RNFirebase, inside that class there are several static methods with no implementation. Create one function doing nothing in the class with the name app.
Your default exported class should look something like this now -
export default class RNFirebase {
static initializeApp() {
RNFirebase.firebase = new MockFirebase()
RNFirebase.promises = []
return RNFirebase.firebase
}
static reset() {
RNFirebase.promises = []
RNFirebase.firebase.databaseInstance = null
}
static waitForPromises() {
return Promise.all(RNFirebase.promises)
}
static analytics () {}
static app () {}
}
This should do the trick, however I belive you are extensively using Firebase. In my case a mock implementation as simple as the one I gave you did the trick for me.
If you are extensively using most of the APIs of Firebase then you are bound to get more errors like you just saw because we haven't yet added mock implementations for all the APIs of RNFirebase in our Firebase mock.
If that case shall ever arise, I would suggest that you look at this mock implementation of Firebase which I guess covers the Firebase completely.
Jest runs in node and does not have access to the native apis, so you'll need to mock the react-native-firebase / RNFirebase module for this to work.
see https://github.com/invertase/react-native-firebase/issues/162

Trouble using auth:import function from firebase-tools package as a node.js module

Currently, I am trying to import users with already hashed passwords into Firebase by solely using the 'firebase-tools' package. I am able to list my current projects by using the command:
client.list({
token:fbToken
}).then(function(data){
console.log(data);
});
but am unable to import any users when trying to use the auth:import command.
client.auth:import({
account_file: "driverList.json",
project:"projectName",
token: fbToken,
hash-algo: "BCRYPT"
}).then(function(data){
console.log(data);
});
I believe that this is because the CLI syntax for auth import is not easily translatable to javascript like the other one word commands (list, logout, etc.). I've tried looking at the documentation, but had no luck.
Does anyone have any idea how to go about this issue? Here is a link to the git repo.
I was having trouble with this as well, and it took literally digging around in the library to try and find answers. In the index.js file here you can see alias' for the listed bash commands. So for auth:import you should call client.auth.upload. However I have yet to find any documentation on the arguments you need to use for the node functions. I suspect they are buried in their corresponding alias here, but not even the deploy function there lists the arguments they use for it in the README. If someone finds any documentation on using arguments, I'd love to know as well.

Using Firebase with Webpack and TypeScript

I'm trying to pull some data from a Firebase instance, but am running into an issue when trying to bind it to a variable. I'm using TypeScript and Webpack to build.
main.ts
import * as Firebase from 'firebase';
class filter {
constructor(){
let ref = new Firebase('my-url-here');
}
}
The typings and npm module are installed and working, and Visual Code brings up no errors, but when I hit the browser I get:
ERROR
TypeError: Firebase is not a constructor
..
Logging Firebase to the console returns an object with methods like auth, app and database, but none of these seem to work either (or I'm calling them incorrectly). Any ideas?
A general best practice on how to incorporate Firebase into a Webpack/TypeScript would be just as welcome.
In my project i had the same error: It was caused by the firebase.json file which i guess got picked up by webpack.
As i can only guess why it happened: Webpack creating a symbol "Firebase" which replaced the constructor of firebase itself.
Have you done a firebase init in your directory?
Also see : https://github.com/angular/angularfire2/issues/187

Categories

Resources