I trying to add this statement to my app to forget the known warning:
The behavior for Date objects stored in Firestore is going to change
AND YOUR APP MAY BREAK...
I've wrote:
import * as firebase from 'firebase';
import '#firebase/firestore';
export default class App extends React.Component {
componentWillMount() {
const config = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '...'
};
firebase.initializeApp(config);
const settings = { timestampsInSnapshots: true };
firebase.firestore().settings(settings);
}
This is the way it's suggested by many, like this answer:
Firebase update error: The behavior for date objects stored in Firestore is going to change and your app may break1
I do what it's suggested here but Im unable to get out of this error...
Error: FirebaseError: Unknown option 'timestampsInSnapshots' passed to
function settings(). Available options: host, ssl, credentials
In the latest version of the newest Firestore e.g. version (7.14.0): The setting 'timestampsInSnapshots: true' is no longer required and should be removed.
Related
I'm using Firebase alongside a Nuxt project, in the following plugin, I call onAuthStateChanged to check if the user is already logged in, if he is I set the user state and redirect him to the dashboard like so:
import firebase from 'firebase'
export default ({ store, redirect }) => {
if (!firebase.apps.length) {
const config = {
apiKey: 'AIzaSyDFS8Wk6B7ontvZeargY3z7k0u92EJvlN0',
authDomain: 'jammer-bd4bc.firebaseapp.com',
databaseURL: 'https://jammer-bd4bc.firebaseio.com',
projectId: 'jammer-bd4bc',
storageBucket: 'jammer-bd4bc.appspot.com',
messagingSenderId: '156254683024'
}
firebase.initializeApp(config)
}
firebase.auth().onAuthStateChanged((user) => {
if (user) {
store.commit('auth/setUser', user)
redirect('/dashboard')
} else {
redirect('/')
}
})
}
The plugin is referenced in my nuxt.config.js like so:
plugins: [
'~/plugins/firebase'
],
But the following error appear when we reach the store commit:
Error: [vuex] Do not mutate vuex store state outside mutation handlers
As if I was mutating the state directly in the plugin (when as you can see I am not).
What could be causing this problem?
Its because you are comming firebase user object to your vuex store. And it later can be changed by firestore itself. So the solution is to clone it before commiting into vuex
Yes you are mutating the store.
commit() fires a mutation.
dispatch() fires an action
So the easy workaround is to use dispatch('auth/setUser') which is a very simple action that calls the commit('auth/setUser')
I've used Vue-cli 3 to create a Vue app and I've been trying to incorporate FCM into it. However, I've been working on it for two days and I still cannot get it working.
First, here's my
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase- app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
var config = {
messagingSenderId: "69625964474"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload)
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
}
return self.registration.showNotification(notificationTitle, notificationOptions)
});
```
One solution that sorta works is I moved this file into the public folder and register it in App.vue using
const registration = await navigator.serviceWorker.register(`${process.env.BASE_URL}firebase-messaging-sw.js`)
messaging.useServiceWorker(registration)
However, then I'll be having two service workers (the other one from Vue itself).
I tried to modify vue.config.js instead trying to work with Workbox by adding the following config:
module.exports = {
pwa: {
name: 'My App',
themeColor: '#4DBA87',
msTileColor: '#000000',
appleMobileWebAppCapable: 'yes',
appleMobileWebAppStatusBarStyle: 'black',
// configure the workbox plugin
workboxPluginMode: 'InjectManifest',
workboxOptions: {
// swSrc is required in InjectManifest mode.
swSrc: 'public/firebase-messaging-sw.js'
// ...other Workbox options...
}
}
}
And then register it again in App.vue:
const registration = await navigator.serviceWorker.register(`${process.env.BASE_URL}service-worker.js`)
messaging.useServiceWorker(registration)
Then I got the following error instead:
If you are confused by the files I mentioned or how the directory of my project looks like, what I did was simply creating a PWA using vue-cli 3. And I left most of the structure untouched.
And I set up firebase in main.js:
import firebase from '#firebase/app'
Vue.config.productionTip = false
const config = {
apiKey: process.env.VUE_APP_FIREBASE_API_KEY,
authDomain: process.env.VUE_APP_AUTH_DOMAIN,
databaseURL: process.env.VUE_APP_DATABASE_URL,
projectId: process.env.VUE_APP_PROJECT_ID,
storageBucket: process.env.VUE_APP_STORAGE_BUCKET,
messagingSenderId: process.env.VUE_APP_MESSAGING_SENDER_ID
}
firebase.initializeApp(config)
Then in App.vue:
import firebase from '#firebase/app'
import '#firebase/messaging'
const messaging = firebase.messaging()
messaging.usePublicVapidKey('PUBLIC_KEY')
The service worker is by default disabled in development mode, so running it in development will cause an HTML error page to be returned, this is the reason you are getting text/html error
You can find detailed explanation here LINK
I realize that that there have already been several questions that address this kind of error, but none of them seem to provide the correct solution. I'm following Stephen Grider's React Native course on Udemy.
I'm pretty sure I've followed everything exactly, so I'm guessing the problem might have to do with an update to React or Firebase or something else, but I might be completely wrong. When pressing the button that activates the following code in onButtonPress():
state = { email: '', password: '', error: '' };
//a definition of the component's state, updated with onChangeText
onButtonPress() {
const { email, password } = this.state;
this.setState({ error: ' ' });
firebase.auth().signInWithEmailAndPassword(email, password) //this line is a "promise"
.catch(() => { //if it fails:
firebase.auth().creatUserWithEmailAndPassword(email, password) //also returns a promoise
.catch(() => { //if it also fails to create a username and password:
this.setState({ error: 'Authentication Failed.' });
});
});
}
I get the following error:
Since a lot of solutions on the web dealing with this error have to do with Firebase initialization, here's my code for that:
import React, { Component } from 'react';
import { View } from 'react-native';
import firebase from 'firebase';
import { Header } from './components/common/index.js'; //selects index.js automatically
import LoginForm from './components/LoginForm.js';
class App extends Component {
conponentWillMount() {
//called before render, will automatically be called because it's a life cycle method
firebase.initializeApp({
apiKey: '(I actually have my api key here, I just do not want people to steal it, same with the other values)',
authDomain: 'authenticationtutorial-ee660.firebaseapp.com',
databaseURL: 'my databaseURL',
projectId: 'my projectId',
storageBucket: 'authenticationtutorial-ee660.appspot.com',
messagingSenderId: 'my SenderId'
});
}
render() {
return (
<View>
<Header headerText="Authentication" />
<LoginForm />
</View>
);
}
}
export default App;
Any help would be appreciated. I've been dealing with this error for about a week now, and with no help on the Udemy website, I've turned to Stack Overflow :)
I had a similar issue and I solved it by adding a condition before the class
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
Correct the spelling of conponentWillMount to componentWillMount and correct the spelling of creatUserWithEmailAndPassword to createUserWithEmailAndPassword.
Thanks!
I had a similar issue in a login redirect structure. As you state in your code ComponentWillMount is called before render, but that doesn't mean all promise are resolved when render its called. I've found a workaround by async / awaiting this method.
async conponentWillMount() {
//called before render, will automatically be called because it's a life cycle method
await firebase.initializeApp({
apiKey: '(I actually have my api key here, I just do not want people to steal it, same with the other values)',
authDomain: 'authenticationtutorial-ee660.firebaseapp.com',
databaseURL: 'my databaseURL',
projectId: 'my projectId',
storageBucket: 'authenticationtutorial-ee660.appspot.com',
messagingSenderId: 'my SenderId' }); }
If you make a global reference to firebase, (ex : const storageRef = firebase.storage().ref() ), it will throw this error. But if you initialize that reference under a scope you are using, it works fine.
Try to Call all configuration of firebase in index.js (TOP LEVEL) in REACT NATIVE than share result.
I am trying to navigate to Main Screen and code still work fine if the JS DEBUGGER is ON(running) but the problem is when i try to run my application when JS DEBUGGER is OFF(disable) and try to login at that time "yield put(NavigationActions.navigate({ routeName: 'Main' }));"
this piece code is not redirecting to Main screen.
Given below is my code:
import { NavigationActions } from 'react-navigation';
import { call, put, takeEvery, take } from 'redux-saga/effects';
import { getFirebase } from 'react-redux-firebase';
export function* watchLoginAsync({email, password}) {
try {
const response = yield getFirebase().login({email,password});
if (response.uid) {
// dispatchToMain();
yield put(NavigationActions.navigate({ routeName: 'Main' }));
// yield put({type: LOGIN_SUCCESS });
} else {
yield put({type: LOGIN_FAIL, error: 'Something went wrong seriously!!'});
}
} catch(err => console.log(err))
}
export default function* watchLogin() {
yield takeEvery(LOGIN_REQUESTING, watchLoginAsync);
}
And this the store.js file(where i have integrated redux-saga with react-redux-firebase)
const sagaMiddleware = createSagaMiddleware();
const middleware = [ sagaMiddleware ];
const firebaseConfig = {
apiKey: '******',
authDomain: '****',
databaseURL: '****',
projectId: '****',
storageBucket: '****',
messagingSenderId: '****',
};
const reduxFirebaseConfig = {
userProfile: 'users',
enableLogging: true,
enableRedirectHandling: false,
};
// Add redux Firebase to compose
const createStoreWithFirebase = compose(
reactReduxFirebase(fbConfig, reduxFirebaseConfig),
applyMiddleware(...middleware)
)(createStore);
// Add Firebase to reducers
const rootReducer = combineReducers({
firebase: firebaseStateReducer,
......
});
// Create store with reducers and initial state
const initialState = {}
export default createStoreWithFirebase(rootReducer, initialState);
// when calling saga, pass getFirebase
sagaMiddleware.run(Sagas, getFirebase)
NOTE:
code is totally working fine if JS DEBUGGER IS ON iOS simulator while app is running.
NOTE: code is totally working fine if JS DEBUGGER IS ON iOS simulator while app is running.
In general debugging mode differs from normal execution by timings - e.g. in debug mode some asynchronous action is performed while you are watching values on breakpoint, and also execution in debug mode is much slower due interception ES262-engine actions. You can try to debug more verbosely by using console.log instructions.
Also, supplied source code
const createStoreWithFirebase = compose(
reactReduxFirebase(fbConfig, reduxFirebaseConfig),
applyMiddleware(...middleware)
)(createStore);
does not include mandatory saga initial invoke operation, like sagaMiddleware.run(rootSaga), what's why maybe nothing is executed.
In original documentation it's present: https://github.com/prescottprue/react-redux-firebase/blob/master/docs/recipes/redux-saga.md
I am new to Vue Js and Firebase. I want to learn firebase /firestore db connection ,data in/out but i am not getting any proper documentation or tutorial for the same.Please suggest.
I am using VUE CLI 2.
Create a src/firebaseDb.js file then add the following code to establish the real-time database connection in vue with your Firebase configurations details.
import * as firebase from 'firebase';
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"
}
const firebaseApp = firebase.initializeApp(firebaseConfig);
export const db = firebaseApp.firestore();
You can check this link its quite easy
https://www.positronx.io/vue-js-firebase-build-vue-crud-app-with-cloud-firestore/
i have created firebaseConfig.js file and connect to fire store.
import firebase from 'firebase/app'
require('firebase/firestore');
// Initialize Firebase
var config = {
apiKey: "AIzaSyC944Kh9T_Pcdn-kTZ6LywsIUATJBmQNTI",
authDomain: "halo-care-38f05.firebaseapp.com",
databaseURL: "https://halo-care-38f05.firebaseio.com",
projectId: "halo-care-38f05",
storageBucket: "halo-care-38f05.appspot.com",
messagingSenderId: "682838402004"
};
const firestore =firebase.initializeApp(config);
const db = firebase.firestore();
export default db;