I am very new to Firebase and I have been looking up how to simply send data to Firebase from React Native. So far I have figured out that you have to import
import * as firebase from 'firebase';
and have
const firebaseConfig = {
apiKey: "AAAAAAAAAAAA3HbIO0u6yxU5MsE6FM",
authDomain: "kokeilut.firebaseapp.com",
databaseURL: "https://kokeilut.firebaseio.com",
storageBucket: "kokeilut.appspot.com",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
but the problem is that I don't know how to send data to database.
Please help me with this, my main point is to send Name and highscore of my application.
I Strongly recommend you to read Firebase JavaScript Documentation, which is much clear than my example. Please correct me if I am wrong.
The following is my example code.
This way will allow Firebase create a Unique Id for your object.
firebase.database().ref(url).push(jsonObject).
then((data) => {
dispatch({type:"FULFILLED"})
//success
}).
catch((err) => {
dispatch({type:"REJECTED"})
//error
});
This way will make you create a customerId for your object.
firebase.database().ref(url+customerId).set(jsonObject).
then((data) => {
dispatch({type:"FULFILLED"})
//success
}).
catch((err) => {
dispatch({type:"REJECTED"})
//error
});
First, install firebase: npm install firebase
Then import firebase to your project: import * as firebase from 'firebase';
Then you can write to a database, but make sure that you have created a database in firebase, and you gave permission to write and read.
firebase.database().ref('users/').set({
username: "name",
email: "email",
profile_picture: "imageUrl"
});
Related
Difficulty in setting up this app as firebase, exported from firebase/app doesn't seem to have the firestore() method on it (See attached image). This is my code. Someone please help me fix it.
// Import the functions you need from the SDKs you need
import firebase from 'firebase/app';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "-------",
authDomain: "--------",
projectId: "------------",
storageBucket: "------------",
messagingSenderId: "---------",
appId: "----------"
};
// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig)
export const firestore = firebase.firestore()
Maybe you're using Firestore v9. So you might be using the methods from the old API
You can check what version of firebase you've installed by looking at the major version of the npm package in your package.json
Here is a snippet from the Firestore docs on how to initialize firestore with with the web version v9 (https://firebase.google.com/docs/firestore/quickstart)
// Initialize Cloud Firestore through Firebase
import { initializeApp } from "firebase/app"
import { getFirestore } from "firebase/firestore"
const firebaseApp = initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
const db = getFirestore();
My problem is that my browser is showing that fire store is not able to connect to the backend:
#firebase/firestore: Firestore (9.1.1): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=permission-denied]: Permission denied on resource project MY_PROJECT_ID.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.
My firebase.js code is
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/storage";
const firebaseConfig = {
apiKey: MY_API_KEY,
authDomain: MY_AUTH_DOMAIN,
projectId: MY_PROJECT_ID,
storageBucket: MY_STORAGE_BUCKET_URL,
messagingSenderId: MY_MESSAGING_SENDER_ID,
appId: MY_APP_IP,
measurementId: MY_MEASUREMENT_ID,
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
const storage = firebase.storage();
export { auth, provider, storage };
export default db;
Please help me .
New firebase v(9.1.1) is modular based version. Therefore you have to import everything as named import from respective files.
eg:-
import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'
const firebase = initializeApp({
apiKey: MY_API_KEY,
authDomain: MY_AUTH_DOMAIN,
projectId: MY_PROJECT_ID,
storageBucket: MY_STORAGE_BUCKET_URL,
messagingSenderId: MY_MESSAGING_SENDER_ID,
appId: MY_APP_IP,
measurementId: MY_MEASUREMENT_ID,
})
const firestore = getFirestore()
The method/function way of using firebase is not supported in v(9.1.1), this probably helps with tree shaking(loading only required files/functions, rather than entire library), which saves loading time and creates fast user experience.
For detailed information checkout these videos:-enter link description here
Also check firebase docs:-enter link description here
Can you please try to generate a new firebaseConfig file? You can do that by
Going to your project settings.
At the bottom of the page there's a section called Your apps.
On the top right of that section click the button labeled Add App.
Choose the icon for webapp (3rd from the left).
After choosing a name for the new webapp, you'll get your new fbconfig.
Copy new fbconfig to your project and try again.
Let me know what happens please.
EDIT 0 -
I've been working on my first React Native project using Firebase Auth (plain email&password only).
Signing-in, Signing-out, Resetting passwords, etc... everything is fine, but I'm stuck with one thing and I need help with deleting user.
Because deleting user is a "sensitive" request, Firebase Auth demands re-authenticating the user before actually deleting the user.
This is where I can't figure out how to do it. Even the docs don't tell much. They literally say: "TODO(you): prompt the user to re-provide their sign-in credentials".
ErrorMessage :
TypeError: undefined is not an object (evaluating '_firebase.auth.EmailAuthProvider.credential')
My firebase.js :
import firebase from 'firebase';
const firebaseConfig = { //key hidden here for security reasons
apiKey: apiKey,
authDomain: authDomain,
projectId: projectId,
storageBucket: storageBucket,
messagingSenderId: messagingSenderId,
appId: appId,
measurementId: measurementId
};
const app = !firebase.apps.length
? firebase.initializeApp(firebaseConfig)
: firebase.app();
const db = app.firestore();
const auth = firebase.auth();
export {db, auth};
My component.js :
...
import { auth } from '../firebase/firebase';
...
const deleteUser = () => {
const user = auth.currentUser;
const credential = auth.EmailAuthProvider.credential(userEmail,userProvidedPassword);
user.reauthenticateWithCredential(credential).then(() => {
user.delete().then(() => {
auth.signOut();
}).catch((error) => {
console.log(error.message);
});
}).catch((error) => {
console.log(error.message);
});
}
You cannot delete users from the front-end React Native!
Instead, there is firebase admin SDK which allows you to delete users but it has to be done from the backend. I believe this link to Firebase Admin SDK will answer your questions.
Also, do check Firebase Cloud Functions if you don't have a backend and you are just relying on Firebase.
Cloud Functions allows you to create a function in Firebase that you can call from React Native using Firebase SDK and perform delete user operation also you could watch for a collection and send notification and do more stuff!
And it is simple than it sounds!
I did a research but found that problem only in node.js context, or react context but from a long time ago, and guys say that upgrading their firebase helped. Mine was installed just last month.
Basically I'm using React with firebase api, and I this code:
firebase.auth().signInWithEmailAndPassword('an email', 'a password);
Throws the following error:
TypeError: WEBPACK_IMPORTED_MODULE_2__firebase.a.auth is not a function
Of course I'm importing firebase:
import firebase from '../../firebase';
All the other firebase commands work just fine.
Has anyone had an experience with that problem using react.js ?
Thanks a lot in advance
Just posting the answer, maybe to help others. The simple solution (thanks to think-twice) is to import "firebase/auth". Here is an example of the Firebase file:
import firebase from 'firebase/app';
import 'firebase/storage';
import "firebase/database";
import "firebase/auth"
// Initialize Firebase
var config = {
apiKey: "*********************",
authDomain: "...",
databaseURL: "...",
projectId: "....",
storageBucket: "....",
messagingSenderId: "..."
};
firebase.initializeApp(config);
const storage = firebase.storage();
export {
storage, firebase as default
}
First check your path is correct, if is, try to delete the node_modules folder and make npm install again !
I'm developing a React app created with "create react app" (https://github.com/facebookincubator/create-react-app).
It will be hosted in Firebase Hosting and I'll like to use implicit initialization as describe in documentation (https://firebase.google.com/docs/web/setup#sdk_imports_and_implicit_initialization), to deploy to multiple projects (I have a dev project and several production projects)
<script src="/__/firebase/init.js"></script>
I need to get the "firebase" object initialized in the script above in my React components. How should I import it in multiple React components files?
I'm aware that this will be only available when I serve it with "firebase serve" during development and when I deploy it, so during development I'm trying to add
<script src="https://www.gstatic.com/firebasejs/4.1.1/firebase.js"></script>
<script>
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
var config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
};
firebase.initializeApp(config);
</script>
code to my index.html file as describe in Firebase docs. However, when I try to import Firebase in ReactComponent it doesn't find it or complains about not initialize project (what I'm doing in the html tag)
How do I import Firebase initialized App and Firebase libraries from my html script tags??
As you are using create-react app and thus webpack, you should already be using nodejs firebase:
npm install --save firebase
To get the config on the fly when deployed, you have to access this url:
/__/firebase/init.json
So you need to make an async call to get the json object stored on this location, before you try to initiliaze firebase. So here is some sample code (using axios for the async call) to include in your index.js:
import React from "react";
import ReactDOM from "react-dom";
import * as firebase from "firebase/app";
import axios from "axios";
const getFirebaseConfig = new Promise((resolve, reject) => {
axios
.get(`/__/firebase/init.json`)
.then(res => {
resolve(res.data);
})
.catch(err => reject(err));
});
getFirebaseConfig
.then(result => {
firebase.initializeApp(result);
ReactDOM.render(
<div>XXXXX</div>,
document.getElementById("root")
);
})
.catch(err => console.log(err));
Also in order to make this more streamlined (use dev firebase config with npm start, and get prod firebase configurations on the fly if deployed) you can do something like the below:
fbconfig.js:
if (process.env.NODE_ENV === "production") {
module.exports = require("./prod");
} else {
module.exports = require("./dev");
}
dev.js:
const firebaseConfig = {
// your dev firebase configuration
apiKey: "xxxxx",
authDomain: "xxxxx",
databaseURL: "xxxxxx",
projectId: "xxxxxx",
storageBucket: "xxxxx",
messagingSenderId: "xxxxx"
};
const getFirebaseConfig = new Promise((resolve, reject) => {
resolve(firebaseConfig);
});
export default getFirebaseConfig;
prod.js:
import axios from "axios";
const getFirebaseConfig = new Promise((resolve, reject) => {
axios
.get(`/__/firebase/init.json`)
.then(res => {
resolve(res.data);
})
.catch(err => reject(err));
});
export default getFirebaseConfig;
And finally in index.js:
import getFirebaseConfig from "./fbconfig";
getFirebaseConfig.then(result => {
firebase.initializeApp(result);
...etc
)}
.catch(err => console.log(err));
You're providing the firebase API directly in the browser with a script tag. It's already going to be available in the browser when you run your bundle.
You're using webpack behind the scenes with create-react-app, but I think you might need to eject it so you can tell it that this package is going to be available on your environment (browser) using the externals property.
https://webpack.js.org/configuration/externals/
From what I understand from this issue, it's not possible to add externals to webpack using create-react-app.
https://github.com/facebook/create-react-app/issues/780
Maybe it's best to drop the <script> tag with the firebase and just install and import it directly on your CRA project.
This might help:
https://www.codementor.io/yurio/all-you-need-is-react-firebase-4v7g9p4kf
Just try to install firebase package via npm. Then you can easily use it wherever you want in any react component by importing with
import firebase from 'firebase';
You can also import firebase in some configureFirebase.js file where you can initialize firebase app with some configs, then export configured firebase instance and use this instance in any component
Its would be helpful:
import firebase from 'firebase'
const config = { /* COPY THE ACTUAL CONFIG FROM FIREBASE CONSOLE */
apiKey: "unreadablestuff",
authDomain: "your-domain-name.firebaseapp.com",
databaseURL: "https://your-domain-name.firebaseio.com",
storageBucket: "your-domain-name.appspot.com",
messagingSenderId: "123123123123"
};
const fire = firebase.initializeApp(config);
export default fire;