bundling failed: SyntaxError: Unexpected end of JSON input in react native - firebase

i am using firebase in my react native project. when i am try to sign up user with email and password this error is comming.
i am using window OS and only andorid render
Note: i had read all questions related to this but nothing helped
newbiew to react native .please guide in proper way
package.json
"firebase": "^5.8.2",
"native-base": "^2.11.0",
"react": "16.6.3",
"react-native": "^0.57.8",
"react-native-elements": "^0.19.1",
"react-native-firebase": "^5.2.2",
"react-native-gesture-handler": "^1.0.15",
"react-native-maps": "^0.23.0",
"react-native-svg": "^8.0.10",
"react-native-vector-icons": "^6.2.0",
"react-navigation": "^3.2.1"
Code for sign up
import * as firebase from 'firebase'
//Intiazlize firebase
const firebaseConfig = {
apiKey: "AIzaSyCUK5QkcvTcvfCKlbwnnI8GskIgcLGMcqA",
authDomain: "trailertracker-da09c.firebaseapp.com",
databaseURL: "https://trailertracker-da09c.firebaseio.com",
projectId: "trailertracker-da09c",
storageBucket: "",
}
firebase.initializeApp(firebaseConfig)
signUpUser = (email,password) => {
try{
if(this.state.password.length < 6 ){
alert("Please Enter Valid Email and Password")
return
}
firebase.auth().createUserWithEmailAndPassword(email,password)
} catch(err){
console.log(err)
}
}
Complete error is
Loading dependency graph, done. error: bundling failed: SyntaxError:
Unexpected end of JSON input
at JSON.parse ()
at FileStore.get (F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro-cache\src\stores\FileStore.js:26:19)
at F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro-cache\src\Cache.js:76:40
at Generator.next ()
at step (F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro-cache\src\Cache.js:18:30)
at F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro-cache\src\Cache.js:37:14
at new Promise ()
at F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro-cache\src\Cache.js:15:12
at Cache.get (F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro-cache\src\Cache.js:102:7)
at F:\React Native\ReactProjects\trailer-tracker\TrailerTracker\node_modules\metro\src\DeltaBundler\Transformer.js:166:34
BUNDLE [android, dev] ....../index.js 68.2% (947/1147), failed.
is this another error or error in firebase ?
Help will be highly appreciated
Thanks

To get started with firebase in react native.
add firebase dependency
yarn add firebase
Goto Firebase and make a new project and going to the section
Add Firebase to your web app
Make a class for configation of Firebase like this
import firebase from "#firebase/app";
require("firebase/database");
require("firebase/storage");
require("firebase/auth");
let config = {
apiKey: "YOUR PROJECT apiKey",
authDomain: "YOUR PROJECT authDomain",
databaseURL: "YOUR PROJECT databaseURL",
projectId: "XXXXXXXX",
storageBucket: "",
messagingSenderId: "XXXXXXXXXX",
appId: "XXXXXXXXXXXXXXXXXXXXXXXX"
};
export default class DBHandler {
static auth;
static database;
static init() {
firebase.initializeApp(config);
DBHandler.database = firebase.database();
DBHandler.auth = firebase.auth();
}
}
in App.js initialize Firebase
import DBHanlder from "./src/api/constants";
export default class App extends Component {
componentDidMount = () => {
DBHanlder.init();
};
render() {
return <YourApp />;
}
}
Your're done with initialization part .now you can use for auth like below
import DBHandler from "../api/constants";
class Login extends Component {
signinUser = () => {
DBHandler.auth.signInWithEmailAndPassword(email, password)
.then(() => {
//Do what you want
})
.catch((error) => {
//handle error
var errorCode = error.code;
var errorMessage = error.message;
alert(errorMessage);
console.log("ERROR");
console.log(errorCode, errorMessage);
});
}
}}

Related

Firebase authentication not working in NuxtJs application

In am using Firebase Authentication in my Nuxt App. I am following the Firebase Documentation for setting up Authentication using GoogleAuthProvider. In my case, onAuthStateChanged() listener returns null even after successfull redirect.
When the user enter my web application, Nuxt will execute the plugin in the client side. There the firebase configuration is initialized. Then the initUser() function defined in useFirebaseAuth.ts composable is called. If user successfully logged In, log the user details.
Note : After I encountered this error, I replaced signInWithRedirect to signInWithPopup, it works very well.
// plugins/firebase.client.ts
import { initializeApp } from "firebase/app";
import { initUser } from "~~/composables/useFirebaseAuth";
export default defineNuxtPlugin(() => {
const config = useRuntimeConfig();
const firebaseConfig = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
appId: "...",
messagingSenderId: "...",
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
initUser(firebaseApp);
})
// composables/useFirebaseAuth.ts
import { FirebaseApp } from "firebase/app";
import { getAuth,signInWithPopup, GoogleAuthProvider, onAuthStateChanged, signInWithRedirect, signOut, User } from "firebase/auth";
import { equalTo, getDatabase, onValue, orderByChild, query, ref as dbRef } from "firebase/database";
export const signInUser = async () => {
const provider = new GoogleAuthProvider();
const auth = getAuth();
await signInWithRedirect(auth, provider)
}
export const initUser = async (firebaseApp: FirebaseApp) => {
const auth = getAuth(firebaseApp)
const db = getDatabase()
onAuthStateChanged(auth, user => {
if (user) {
console.log(user)
} else {
console.log("user not logged in"
return navigateTo('/login')
}
});
}
export const signOutUser = async () => {
const auth = getAuth();
await signOut(auth)
}
In the above code, I always get the user value as null. I am working on the project for 2 months. The authentication works fine almost one month ago. But it is not working now. Please help me to resolve the issue.
# node --version
v19.5.0
# npm version
{
npm: '9.3.1',
node: '19.5.0',
v8: '10.8.168.25-node.11',
uv: '1.44.2',
zlib: '1.2.13',
brotli: '1.0.9',
ares: '1.18.1',
modules: '111',
nghttp2: '1.51.0',
napi: '8',
llhttp: '8.1.0',
uvwasi: '0.0.14',
acorn: '8.8.1',
simdutf: '3.1.0',
undici: '5.14.0',
openssl: '3.0.7+quic',
cldr: '42.0',
icu: '72.1',
tz: '2022g',
unicode: '15.0',
ngtcp2: '0.8.1',
nghttp3: '0.7.0'
}
I have gone through many answers posted for same question in the stackoverflow website. But those answers didn't solved my issues.

firebaseConfig.default.auth promise rejection error

I am trying to signup user with facebook but i am seeing very rigid error and it seems there is no solved help out there so i am asking again
thats my code
async function signInWithFacebook() {
// const appId = Expo.Constants.manifest.extra.facebook.appId;
Facebook.initializeAsync(appid)
const permissions = ['public_profile']; // Permissions required, consult Facebook docs
const {
type,
token,
} = await Facebook.logInWithReadPermissionsAsync(
{permissions}
);
if(type == "success"){
const credential = initFirebase.auth.FacebookAuthProvider.credential(token);
initFirebase.auth().signInWithCredential(credential)
.catch(err => {
console.log(err)
})
}
}
i am using appid in strings but i have not added it here hope you understand that.
and the error is this
this is my firebase config file code
import firebase from "firebase/app"
import "firebase/firestore"
import "firebase/auth"
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "xxxxxxxx",
authDomain: "xxxxxx",
databaseURL: "xxxxxx",
projectId: "xxxx",
storageBucket: "xxxxx",
messagingSenderId: "xxxxx",
appId: "xxxxx"
};
// Initialize Firebase
const initFirebase = firebase.initializeApp(firebaseConfig);
export default initFirebase
variable values are hidden because of privacy .i worked with firestore and that worked but i am seeing issue with auth with facebook .
i am using react native , firebase , expo and not firebase sdk
You don't have to register a Facebook App for Login with Facebook using Firebase. You can use the below code with Firebase Facebook Authentication enabled in the console.
export const loginWithFacebook = (accessToken) => {
const credential = initFirebase.auth.FacebookAuthProvider.credential(accessToken);
return new Promise((resolve, _reject) => {
signInWithCredential(credential).then(response => {
resolve(response);
});
});
};

NextJS: Accessing Google Firestore data

So I'm not sure how to do this exactly. Here is what I have:
In my Index.js I have
Index.getInitialProps = async function () {
const firebase = require('firebase')
const firebaseConfig = {
apiKey: "examplezbxW_9nKoUjas",
authDomain: "example-prod.firebaseapp.com",
databaseURL: "https://example-prod.firebaseio.com",
projectId: "example-prod",
storageBucket: "example-prod.appspot.com",
messagingSenderId: "1234567890",
appId: "1:1234567890:web:1234567890"
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
const db = firebase.firestore()
const data = db.collection('data').get()
return {
data
}
}
This gives me an error of FirebaseError: projectId must be a string in FirebaseApp.options
(Maybe I need to run the firebase node package and login...)
It says the error is occurring at this line const db = firebase.firestore()
Any help is appreciated. Maybe this isn't the spot I should be trying to load firestore data... not sure.
I also considered creating a node server and doing it that way, but ideally, I'd like to avoid that.
Okay, so there was a couple changes I made to fix this.
I moved my firebase initialization to another file and that file looked like this:
import firebase from 'firebase/app'
import 'firebase/firestore'
export function loadDB() {
try {
var config = {
apiKey: "YOUR INFO HERE",
authDomain: "YOUR INFO HERE.firebaseapp.com",
databaseURL: "https://YOUR INFO HERE.firebaseio.com",
projectId: "YOUR INFO HERE",
storageBucket: "YOUR INFO HERE.appspot.com",
messagingSenderId: "YOUR INFO HERE",
appId: "YOUR INFO HERE"
};
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);
}
}
return firebase;
}
Then, in my NextJS componenet, in the getInitialProps method, I have:
import { loadDB } from '../lib/db'
Index.getInitialProps = async function () {
const db = await loadDB()
let data = []
const querySnapshot = await db.firestore().collection('data').get()
querySnapshot.forEach(doc => {
data.push(doc.data())
})
return {
data
}
}

React Native Firebase Auth function

I'm using react native crud application with using firebase real time storage. I use firebase auth functionality with email and password logging. but my firebase auth is not working. It gets more issues with firebase connection. I used this function to connect firebase.
componentWillMount() {
firebase.initializeApp({
apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxx',
authDomain: 'xxxxxxxxxxxxxxxxxxxxxx',
databaseURL: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
projectId: 'xxxxxxxxxxxxxxxxxxxxx',
storageBucket: 'xxxxxxxxxxxxxxxxxxxxxxxx',
messagingSenderId: 'xxxxxxxxxxxxxxx'
});
}
My log in button auth functionality is looks like this one:
state = { email: '', password: '', error: '' };
onButtonPress() {
const { email, password } = this.state;
firebase.auth().signInWithEmailAndPassword(email, password)
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.catch(() => {
this.setState({ error: 'Authenticaton Failed.' });
});
});
}
I import firebase libraries like this:
import * as firebase from 'firebase';
import 'firebase/firestore';
import 'firebase/auth';
But this configurations are not working. It shows me this error:
undefined is not a function (evaluating 'firebase.auth()')
I used to get text input values this method:
value={this.state.password}
onChangeText={password => this.setState({ password })}
your firebase config only exists in your componentDidMount. Try like this:
Create a file <namefile>.js wherever you want and add:
import * as firebase from 'firebase'
import 'firebase/auth';
const config = {
apiKey: "your key",
authDomain: "domain",
databaseURL: xxxx",
projectId: "xxxx",
storageBucket: "xxx",
messagingSenderId: "xxxx"
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
const auth = firebase.auth();
export {
auth
};
import auth in your component and in your button method change your code by:
auth.signInWithEmailAndPassword
it should work and every time you need to use auth, you just need to import it

Connect Firebase with React Native

I'm trying to connect React Native with Firebase. I'm using the following method to connect Firebase.
import * as firebase from 'firebase';
// Initialize Firebase
const firebaseConfig = {
apiKey: "<YOUR-API-KEY>",
authDomain: "<YOUR-AUTH-DOMAIN>",
databaseURL: "<YOUR-DATABASE-URL>",
storageBucket: "<YOUR-STORAGE-BUCKET>"
};
firebase.initializeApp(firebaseConfig);
app.authWithPassword({
"email": "abc#abc.com",
"password": "abc1234"
}, (error, user_data) => {
if (error) {
alert('Login Failed. Please try again');
} else {
AsyncStorage.setItem('user_data', JSON.stringify(user_data));
}
});
But it returns the following error:
app.authWithPassword is not a function.
I'm using Firebase 3.4 and React Native 0.32.
From the Firebase documentation:
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});

Resources