Fetching from Firestore URL shows 404 - URL not right? - firebase

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

Related

Using firebase cloud functions with realtime db throws a Client is Offline error [duplicate]

Using React with NextJS the following error occurs occasionally when fetching data from a Firebase Realtime Database.
Unhandled Runtime Error
Error: Error: Client is offline.
I am using Firebase 9.0.1 for React.
Top Level code for intialisation and config
import { initializeApp } from "firebase/app";
import { getDatabase, ref, onValue, child, get } from "firebase/database";
import CONFIG from '../CONFIG.json'
const FIREBASE_CONFIG = {
apiKey: CONFIG['FIREBASE_API_KEY'],
authDomain: CONFIG['FIREBASE_AUTH_DOMAIN'],
databaseURL: CONFIG['FIREBASE_DATABASE_URL'],
storageBucket: CONFIG['FIREBASE_STORAGE_BUCKET']
}
const fbApp = initializeApp(FIREBASE_CONFIG)
And later fetching data
export default function Leads() {
...
useEffect(() => {
const database = getDatabase(fbApp)
const ads = ref(database, 'ad_results')
get(ads).then((snap) => {
const results = snap.val()
...
I have tried searching similar issues but to no avail, any help would be appreciated.
I had the same issue with my Cloud Functions, which was very confusing. After some hours of debugging, I found out that the .get() method of the Realtime Database was causing this problem. My current workaround is to use instead .once('value').
So I changed my code from:
await database.ref(`foo/bar`).get();
to
await database.ref(`foo/bar`).once('value');
I am using firebase nodejs SDK, also facing the same error: "Error: Error: Client is offline." occasionally.
I have tried the above solution posted by Nils Reichardt. It works for me.
Thanks Nils!

Using with Firebase / Expo query to Cloud Firestore

So I am trying to keep my code clean and build different files for querying... So I may be taking this harder than it needs to be.
I building a react-native app using Expo CLI.
I have created 3 files, one is my firebase config file,
one is a query file
then the actual file that is using that query.
it looks ok to me... but I get this error.
TypeError: undefined is not an object(evaluating'_firebase.firebase.firestore')
Here is my config file
import * as firebase from "firebase";
import 'firebase/firestore';
const firebaseConfig = {
apiKey: "api-key",
authDomain: "project-id.firebaseapp.com",
databaseURL: "https://project-id.firebaseio.com",
projectId: "project-id",
storageBucket: "project-id.appspot.com",
messagingSenderId: "sender-id",
appId: "app-id",
measurementId: "G-measurement-id"
};
firebase.initializeApp(firebaseConfig);
Then I have a a query file, basically acting as the API layer
import { firebase } from "./firebase";
const db = firebase.firestore();
const getListings = () => {
db.collection("listings").get();
};
export default {
getListings,
};
Then I am trying to view the queried data.
import listingApi from "../api/listings";
function ListingsScreen({ navigation }) {
const [listings, setListings] = useState([]);
useEffect(() => {
loadListings();
}, []);
const loadListings = async () => {
const response = await listingApi.getListings();
setListings(response.data);
};
This is my first time ever using Firebase or cloud firestore... so im really confused.
The error message is telling you that '_firebase.firebase.firestore' data is returning as undefined, this means the document you requested doesn't exist.
At the officiald documentation of Expo, is recommended to put the firebase config information in the same file with your code in order to use firebase, for example:
import * as firebase from 'firebase'
import 'firebase/firestore';
const firebaseConfig = { ... } // apiKey, authDomain, etc. (see above)
firebase.initializeApp(firebaseConfig);
const dbh = firebase.firestore();
dbh.collection("characters").doc("mario").set({
employment: "plumber",
outfitColor: "red",
specialAttack: "fireball"
})

How to use Firebase Cloud FireStore Database in a Next JS project. How to initialize it correctly?

On a firebase.js file I am doing this:
import firebase from "firebase/app";
import "firebase/firestore";
const firebaseConfig = {
apiKey: process.env.APIKEY,
authDomain: process.env.AUTHDOMAIN,
databaseURL: process.env.DATABASEURL,
projectId: process.env.PROJECTID,
storageBucket: process.env.STORAGEBUCKET,
messagingSenderId: process.env.MESSAGINGSENDERID,
appId: process.env.APPID,
measurementId: process.env.MEASUREMENTID
};
export function firebaseDB() {
// Initialize Firebase
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
// firebase.analytics();
}
return firebase;
}
Then, on pages/index.js I am using the getInitialProps:
App.getInitialProps = async () => {
const firebaseDatabase = await firebaseDB();
const db = firebaseDatabase.firestore();
let result;
db.collection("users")
.add({
first: "Ada",
last: "Lovelace",
born: 1815
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
result = { docs: docRef };
})
.catch(function(error) {
console.error("Error adding document: ", error);
result = { error: error };
});
return result
};
I am assuming that because of the asynchronous nature I am returning the result variable undefined and getting this error:
"App.getInitialProps()" should resolve to an object. But found "undefined" instead.
So, I am not happy with the way I am configuring this...can someone throw some light?
Here are some of the ways I can think of:
Create an HOC for it and wrap the page components that will be using it. (https://medium.com/#uvictor/simple-firebase-authentication-with-next-js-using-hoc-higher-order-components-8e8931d25cfa)
Initialise it in the Root component and pass the DB ref to the children. For example, in your Root component, you declare your routes there. What you wanna do is pass the DB ref to each of the components under it. Though this might be problematic when you wanna do SSR. Not sure how would this play out.
If only a single page will be using Firebase (happened to me a couple of times), just do it like what you are doing right now.
If you are thinking of using Redux, you might want to initialise firebase and bind it to the store (https://github.com/prescottprue/react-redux-firebase)
My suggestion is, try not to overcomplicate it. Do what works for you.

null returned when fetching data from firebase using expo

I'm trying to fetch data from firebase in my expo app
so this is the component where I implement this code:
import firebase from 'firebase';
// Initialize Firebase
var config = {
apiKey: "AIzaSyAVf",
authDomain: "d07f5.firebaseapp.com",
databaseURL: "https://d07f5.firebaseio.com",
projectId: "d07f5",
storageBucket: "d07f5.appspot.com",
messagingSenderId: "66392528"
};
firebase.initializeApp(config);
const api =
firebase.database().ref('/Barbers').on('value', (snapshot) => {
console.log('testing')
console.log(snapshot.val())
});
export default {
getBarbersShops,
}
when I run the app on my android device and seeing the remote debugging from the console of browser I find the " testing " word that I write in console but for this console:
console.log(snapshot.val())
I just got null for it and can't understand why?
and this is image for collection in firebase:
You're getting null because your code is accessing Firebase Realtime Database, but the picture of your data is showing it stored in Cloud Firestore. These are not the same products - they share neither the same data nor the same APIs.
doug stevensons answer is totally right! To get the document from firestore in react native, you can use the following code:
import firebase from 'react-native-firebase'
myFunction(){
firebase.firestore().collection('Barbers').doc('9R4t...').get().then(doc => {
if(doc.exists){
console.log(doc.data().name); // testing
}
}
}
or async:
async myFunctionAsync(){
const doc = await firebase.firestore().collection('Barbers').doc('9R4t...').get();
if(doc.exists){
console.log(doc.data().name); // testing
}
}

Firebase: Update Firestore Fails If Document Does Not Exist [duplicate]

This is my very basic Cloud Function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore()
exports.createdNewAccount = functions.auth.user().onCreate(event => {
return db.collection('users').doc(event.data.uid).update({
"creationDate" : Date.now()
})
})
And I get the error
Error: no entity to update: app
What is wrong with my code?
Most likely, the document for event.data.uid does not exist. The documentation for update() states:
The update will fail if applied to a document that does not exist.
Use set() instead.
I faced a similar error when testing my app locally with the Firebase emulator. My firebase config file looked like:
import firebase from "firebase";
import "firebase/firestore";
const firebaseConfig = {
apiKey: <FIREBASE_API_KEY>,
authDomain: <FIREBASE_AUTH_DOMAIN>,
databaseURL: <FIREBASE_DB_URL>,
projectId: <FIREBASE_PROJECT_ID>,
storageBucket: <FIREBASE_STORAGE_BUCKET>,
messagingSenderId: <FIREBASE_MSG_SENDER_ID>,
appId: <FIREBASE_APP_ID>,
measurementId: <FIREBASE_MEASUREMENT_ID>,
};
// Initialize Firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
// for local instances, use the emulator to connect the frontend to firestore & functions
if (location.hostname === "localhost") {
firebase.firestore().settings({
host: "localhost:8080",
ssl: false,
});
firebase.functions().useFunctionsEmulator("http://localhost:5001");
}
Turns out my local Firestore database (expected to be running at localhost:8080) wasn't being hit. So my cloud functions were trying to write to a non-existent db. The underlying issue was that I also had my backend initializing to a different database:
// functions/index.js
const admin = require("firebase-admin");
var serviceAccount = require("./serviceAccount.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://other-firebase-project-id.firebaseio.com",
});
The solution (originally adapted from a Fireship tutorial) was to remove this [incorrect] re-initialization of the database altogether:
// functions/index.js
...
admin.initializeApp();
...
After all, according to the docs, we can initialize the Firebase Admin SDK without parameters since the FIREBASE_CONFIG environment variable is included automatically in Cloud Functions for Firebase functions that are deployed via the Firebase CLI.
FWIW, also be sure to set the correct Firebase project on the CLI. Doing so with this allows the Firebase CLI to hook Functions/Firestore to the right project:
firebase use <desired-firebase-project-id>
If you have multiple Firebase projects, you can list them out with: firebase projects:list

Resources