Can not access to firebase.database.ServerValue.TIMESTAMP in React-Native - firebase

After upgraded to Firebase 3.2.0 (react-native 0.30), I'm trying to set a TIMESTAMP as described in the docs:
import Firebase from 'firebase'
...
let config = {
apiKey: `${ Config.firebase.apiKey }`,
authDomain: `${ Config.firebase.authDomain }`,
databaseURL: `${ Config.firebase.databaseURL }`,
storageBucket: `${ Config.firebase.storageBucket }`
}
const firebase = Firebase.initializeApp(config)
const created_at = firebase.database.ServerValue.TIMESTAMP
then I get
created_at = undefined
when debugging with Chrome' Developer Tools, firebase.database is a function without any ServerValue in it.
Any idea ?

Try this syntax:
import Firebase from 'firebase'
and then:
Firebase.database.ServerValue.TIMESTAMP

This works for me
import RNFirebase from "react-native-firebase"
data.timestamp = RNFirebase.database.ServerValue.TIMESTAMP;

In my case, even though I was using Firestore for all my data storage/retrieval using the web JS client, I had to import the Firebase Database libary at the start of my HTML like so
<script defer src="/__/firebase/7.17.1/firebase-database.js"></script>
Simply having <script defer src="/__/firebase/7.17.1/firebase-firestore.js"></script> is not enough. After loading the database module, then I could access firebase.database stuff, like ServerValue.TIMESTAMP
In my case, since I am using Firestore, then I used firebase.firestore.Timestamp.now() instead of the firebase.database bits above.

Related

Fetching from Firestore URL shows 404 - URL not right?

I am using Next.js to fetch data from my Firestore Database, but I keep getting an error in the console, stating that GET (FirestoreDatabaseURL) 404 (not found).
When I try any other json database such as myfakestore or jsonplaceholder, my code works (I tried both getServerSideProps and fetching with UseState), works beautifully. But not from my own database. Tried with Postman, but it won't work either.
I have tried to find different ways to get the database URL, but I am only finding this one format:
https://PROJECTID.firebaseio.com
The server is in us-central, which also helps determine the URL.
While testing around, I have gotten the error FetchError: invalid json response body at https://PROJECTID.firebaseio.com/ reason: Unexpected token F in JSON at position 0
Which I came to find out that it's not actually returning json, but HTML.
Just for context, this is my working code:
const [showProducts, setShowProducts] = useState()
const apiData = 'https://celeste-73695.firebaseio.com/'
let displayProducts
function pullJson () {
fetch(apiData)
.then(response => response.json())
.then(responseData => {
displayProducts = responseData.map(function(product){
return (
<p key={product.id}>{product.title}</p>
)
})
console.log(responseData)
setShowProducts(displayProducts)
})
//return
}
useEffect(() => {
pullJson()
},[])
And my firebase.js file
import firebase from 'firebase';
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "***",
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
};
const app = !firebase.apps.length
? firebase.initializeApp(firebaseConfig)
: firebase.app();
const db = app.firestore();
export default db;
Can anybody point me in the right direction?
Thanks in advance.
The databaseURL property is for the Firebase Realtime Database, which you probably didn't create yet. The databaseURL property is not necessary to use Firestore though, so you should be able to access that with just the configuration data you have.
You may have created the realtime database but not have configured it with firebase config. I recommend you to go through this documentations for the realtime database.
To configure the firebase firestore you need to do the following:
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
// ...
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);
And make sure to export the db reference as will be used in your project.
After that you can start using the firestore like documented here as you have tried to use it with URL you may have to change the implementation for using it like shown in above documentations

WebConfig doesn't return measurementId

I am trying to enable firebase analytics in my existing firebase project. The project is a static React website that only uses Firebase hosting.
Following this get start tutorial, I am getting the following error in my console:
Ignored "config" command. Invalid arguments found
Searching how to solve this problem, I found this comment and checked that my webConfig get request is not returning the measurementId. However I couldn't find any info about how to correct it.
//firebase.js
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics} from "firebase/analytics";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "{ApiKey}",
authDomain: "{projectId}.firebaseapp.com",
projectId: "{projectId}",
storageBucket: "{projectId}.appspot.com",
messagingSenderId: "{messagingSenderId}",
appId: "{appId}",
measurementId: "{measurementId}",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const analytics = getAnalytics(app);
WebConfig call (Http 200, Get):
response:
{
"projectId": "{projectId}",
"appId": "{appId}",
"storageBucket": "{projectId}.appspot.com",
"authDomain": "{projectId}.firebaseapp.com",
"messagingSenderId": "{messagingSenderId}"
}
Is there any config that I am missing? what should I do to make it work?
There could be something wrong with the stream for your web app that’s why the measurementId is not being configured. You could try to unlink and relink to your Google Analytics integration which usually resolves any broken integration. Make sure that the currently linked GA property is the one you’re going to use for relinking to avoid losing your data.

How to use process.env on apollo-client? [duplicate]

I've been poking around with this for at least an hour and so far I'm stumped. Perhaps I'm not understanding the docs or the medium articles. But, as I understand it NextJS (I have have the latest version installed) provides a built in env variable solution. So, there is no need for the dotenv package.
Since NextJS is setup all I would need to do is create an env.local to store my API_KEY and other sensitive information. Then, once I save that updated file, I should be able to access ${process.env.API_KEY} and have access to that value anywhere in my code.
Provided the above statements are true, I'm not able to get that to work.
In my case I'm using environmental variables to connect to Firebase. In the code below it's being implemented. I get a 500 malformed error:
Connection GRPC stream error. Code: 3 Message: 3 INVALID_ARGUMENT:
Project id parakeat-a1-7706, is malformed: it either contains invalid
characters or is too long. Look at https://cloud.google.com
/resource-manager/docs/creating-managing-projects#identifying_projects
for instructions in how to get a project's id.
import * as firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/storage';
import 'firebase/analytics';
const config = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
measurementId: process.env.FIREBASE_MEASUREMENT_ID,
};
// Initialize Firebase
try {
firebase.initializeApp(config);
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack);
}
}
// const firebaseAnalytics = firebase.analytics();
const firebaseStorage = firebase.storage();
const firebaseFirestore = firebase.firestore();
export { firebaseStorage, firebaseFirestore };
The ID is correct shown above, so what's wrong? Why is it that if I put the actual value directly in and skip the process.env it successfully connects?
By default all environment variables loaded through .env.local are only available in the Node.js environment (in methods like getStaticProps), meaning they won't be exposed to the browser.
In order to expose a variable to the browser, you have to prefix the variable with NEXT_PUBLIC_. For example:
NEXT_PUBLIC_ANALYTICS_ID=abcdefghijk
Docs
I have used the above solution before but later on needed to include my .env variables in the bundle which is why I used the next.config.js file to house my variables.
Check this link to their documentation for reference:
Nextjs - next.config.js

Implement callable cloud functions in Firebase client app

I have recently discovered the Firebase callable functions which allows me to call HTTPS trigger like function from the client side (and with auth() support).
I struggle to implement this new feature in my already existing Firebase web-client application.
I have some cloud functions running, among them are some HTTPS functions I would like to transform into an HTTPS callable function (with functions.https.onCall).
The documentation indicates:
Set up your client development environment
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-functions.js"></script>
And my code is:
import firebase from 'firebase';
import 'firebase/firestore';
const firebaseApp = firebase.initializeApp({
apiKey: '....',
authDomain: '....',
databaseURL: '....',
projectId: '....',
storageBucket: '....',
messagingSenderId: '....',
});
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
const functions = firebaseApp.functions();
export { db, auth, functions };
When I run my app, I got the following error:
Uncaught TypeError: firebaseApp.functions is not a function
I have tried yarn add firebase-functions and then import 'firebase-functions but then the app requires firebase-admin. I am affraid it is too much for a client-app so I might go in the wrong direction.
Can someone help me with this issue?
(!) This issue is NOT about the server-side Firebase SDK for Cloud Functions (Node JS). It is about calling Cloud functions directly from a Firebase web app.
Thank you!
UPDATE:
Thanks to #Andrew's post, this solves my issue:
My configuration
import firebase from 'firebase';
import 'firebase/firestore';
import '#firebase/functions';
import firestoreConfig from '#/config/firestore';
const firebaseApp = firebase.initializeApp(firestoreConfig /* The JSON configuration from my Firebase project */);
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
const functions = firebaseApp.functions();
export { db, auth, functions };
Using the configuration:
import { db, functions } from '#/database/firestoreInit';
export default {
addMessage(text) {
const addMessage = functions.httpsCallable('addMessage');
return addMessage({ text }).then(result => result);
},
}
I just ran into this same problem myself and solved it by installing and importing the #firebase/functions npm package. I found the solution on github here:
https://github.com/firebase/firebase-js-sdk/blob/master/packages/functions/README.md
From the README on github:
ES Modules
import firebase from '#firebase/app';
import '#firebase/functions'
// Do stuff w/ `firebase` and `firebase.functions`
CommonJS Modules
const firebase = require('#firebase/app').default;
require('#firebase/functions');
// Do stuff with `firebase` and `firebase.functions`
Hope that helps! The actual documentation is not very clear about having to do this in order to call the functions.
About #firebase/functions:
This package is not intended for direct usage, and should only be used via the officially supported firebase package.
This worked for me:
import * as firebase from 'firebase/app'; // Typescript
// import firebase from 'firebase/app'; // JS
import 'firebase/functions';
const myCallableFunc = firebase.functions().httpsCallable('myCallableFunc');
I don't know about importing firebase-functions with a CDN but if you're using npm then you don't need the firebase-functions package, just installing firebase will do.
Follow the steps mentioned here. Firebase cloud functions
I think there is nothing like firebaseApp.functions.

Use firebase auto SDK setup with Webpack

I am creating a web app that uses Vue webpack with firebase. I would like to have my firebase credentials automatically change when i use firebase use <some_alias> on the firebase cli. In other projects, this simply meant including the /__/firebase/init.js file of firebase hosting. In this project, I am using the npm firebase library and can load in a specific firebase set of credentials with
import firebase from 'firebase'
var config = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '...'
}
firebase.initializeApp(config)
export default {
database: firebase.database,
storage: firebase.storage,
auth: firebase.auth
}
However, this does not get my credentials based on my current firebase workspace. Instead, I would like something like
import firebase from 'firebase'
const fbcli = require('firebase-tools');
export const getFirebaseInstance = () => {
return fbcli.setup.web().then(config => {
firebase.initializeApp(config)
return firebase
});
}
though synchronous. Is there any way to synchronously load in my firebase credentials?
This was solved by checking window.location.host when in the prod environment and having a production config object if the host was our production hostname and reading from the values of a configuration file otherwise.
Try using fs.writeFileSync as described in this example from a firebase blog post about reading credentials:
const fbcli = require('firebase-tools');
const fs = require('fs');
// by default, uses the current project and logged in user
fbcli.setup.web().then(config => {
fs.writeFileSync(
'build/initFirebase.js',
`firebase.initializeApp(${JSON.stringify(config)});`
);
});

Resources