davideast / firebase-react-native-sample Goto Github PK
View Code? Open in Web Editor NEWUsing React Native with Firebase
Using React Native with Firebase
Is there equivalent of "[Firebase defaultConfig].persistenceEnabled = YES;" or "Firebase.getDefaultConfig().setPersistenceEnabled(true);" on react-native? How to avoid having to re-download the data after the app is quit and re-started? Thanks!
FIREBASE WARNING: set at /items/-KOVBqAEv9fhNCyAjiG_ failed: permission_denied
Possible Unhandled Promise Rejection (id: 0): PERMISSION_DENIED: Permission denied
Got this, when trying to retrieve data
I think is it valuable to consider how to integrate redux with firebase instead query in container directly.
Hello,
As seen, the firebase API has made some changes:
We don't initialize Firebase with a constructor anymore like so:
index.ios.js
getRef() {
return new Firebase(FirebaseUrl);
}
The correct way to do is (according to Firebase's documentation):
var firebase = require("firebase");
firebase.initializeApp({
apiKey: "XXXXX",
authDomain: "XXXXX",
databaseURL: "XXXXX",
storageBucket: "XXXXX",
});
But there is still an error: facebook/react-native#7864
I get this error while running on windows machine.
React native version info
D:\sample-app>react-native --version
react-native-cli: 2.0.1
react-native: 0.29.2
I'm trying to login with Google but it throws me this error:
code: "auth/operation-not-supported-in-this-environment"
message: "This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled."
This is the code:
const provider = new firebase.auth.GoogleAuthProvider();
provider.addScope('profile');
provider.addScope('email');
firebase.auth().signInWithPopup(provider)
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
})
"firebase": "^3.7.1",
"react-native": "^0.42.0",
platform: Android
any ideas?
thanks in advance!
Hi David,
I'm new react-native and firebase. I've seen some of your post online and I know you work very with Firebase. I'm looking for an example react-native app using google authentication I couldn't find it anywhere.
I know Firebase has introduced the new (GoogleAuthProvider and other AuthProviders). I think it would really help the community if you can put together a sample project.
Let me know, how can I help. Thanks @davideast
Diraj
Hey there! I've tried Firebase 3.2.0 on Android in my own react native project and I seem to be running into trouble!
I've setup my config, initialized the app, and then tried logging in anonymously and with emailAndPassword like so:
firebaseApp.auth().signInAnonymously()
.then(function onSignInSuccess() {
console.log("success", arguments)
})
.catch(function onSignInError() {
console.log("Failure", arguments)
})
The problem: On iOS, the promise succeeds or fails as expected, whereas on Android the Promise does not. Any ideas on why or why 3.2.0 might not work for Android yet works fine on iOS? Is RN for Android supported?
SyntaxError /Users/adamclark/repos/FirebaseAuthtest/node_modules/react-native/Libraries/CustomComponents/ListView/ListView.js: A trailing comma is not permitted after the rest element (454:14)
I am getting this error upon cloning and trying to build this example. Not sure if this is happening to anyone else but I have replicated on two machines with xcode 8 and an older version.
I have never seen this in the current react native projects where I am using <ListView/>
Hi @davideast,
I was wondering if you know the reason why createCustomToken
is not supported on react-native, even though it is documented as part of the Node.js SDK https://firebase.google.com/docs/reference/node/firebase.auth.Auth#createCustomToken. It seems that in the past it was possible to create custom tokens by using https://github.com/firebase/firebase-token-generator-node (versions 2.x.x).
Thanks!
I'm trying to signInWithCredential using the idToken that I get using https://github.com/devfd/react-native-google-signin
This is the error that it throws:
code:"auth/internal-error"
message:"{"error":{"errors":[{"domain":"global","reason":"invalid","message":"Invalid Idp Response: the Google id_token is not allowed to be used with this application. Its audience (OAuth 2.0 client ID) is 907575791000-111507729qcg9q903inpunsuaqbfpuga.apps.googleusercontent.com, which is not authorized to be used in the project with project_number: 439665506444."}],"code":400,"message":"Invalid Idp Response: the Google id_token is not allowed to be used with this application. Its audience (OAuth 2.0 client ID) is 907575791000-111507729qcg9q903inpunsuaqbfpuga.apps.googleusercontent.com, which is not authorized to be used in the project with project_number: 444665506444."}}"
In firebase console I've enabled Google provider, also the Google APP ID to the whitelist.
Also the web client ID that I used with react-native-google-signin and the client secret.
Aditional Information:
"firebase": "^3.7.1"
any ideas?
Thanks in advance
May i know what are the current firebase features that work with react-native app?
I already know that Authentication,Login,Realtime Database work other than it what features work ? Please tell me what features also work ?
It has been announced that as of the release of Firebase 3.1.0 Firebase Authentication works with React, however I've found myself having a lot of problems, I haven't gone through the process of attempting a manual automatic login flow using signInWithEmailAndPassword`
The standard callback for managing authorization state changes immediately throws an error, it seems like it's because it's trying to use DOM local storage,
firebase.auth().onAuthStateChanged(...)
The actual callback fires, however immediately after the callback function is executed, you're given an error:
ExceptionsManager.js:78
Unhandled JS Exception: Cannot read property 'getItem' of undefined
Is this expected? I've noticed a few posts about examples using React and Firebase since 3.1, but none of them use Auth.
Hi I am new to Firebase and I am trying to understand this project. One thing that clicked me while I was going through it was will using ComponentWillMount instead of ComponentDidMount cause any performance changes in the long run, I mean with a list as small as 10-20 members it might not be such a difference but with a larger list will there be a difference in rendering of items ?
BTW very helpful blog @davideast
Thanks !!
Hi,
I follow the guide but got that error. Please help.
import React, { Component } from 'react';
import {
Text,
View,
ListView
} from 'react-native';
import * as firebase from 'firebase'
import { constantColor, styles } from './styles'
import ActionButton from './components/ActionButton'
import ListItem from './components/ListItem'
import StatusBar from './components/StatusBar'
// Initialize Firebase
const firebaseConfig = {
apiKey: 'AIzaSyBfvVSh162xtnRiWELB9LWSUodd0-spvCU',
authDomain: 'groceryandroid-df821.firebaseapp.com',
databaseURL: 'https://groceryandroid-df821.firebaseio.com',
storageBucket: ""
};
firebase.initializeApp(firebaseConfig);
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 != row2
})
}
this.itemsRef = this.getRef()
}
getRef() {
const rootRef = firebase.database().ref()
const itemsRef = rootRef.child('items')
return itemsRef
}
componentDidMount() {
this.listenForItems(this.state.itemsRef)
}
_renderItem = (item) => {
return (
<ListItem item={item} onpress={() => { }} />
)
}
listenForItems(itemsRef) {
itemsRef.on('value', (snap) => {
// get children as an array
var items = [];
snap.forEach((child) => {
items.push({
title: child.val().title,
_key: child.key
});
});
this.setState({
dataSource: this.state.dataSource.cloneWithRows(items)
});
});
}
render() {
return (
<View style={styles.container}>
<StatusBar title="Grocery List" />
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderItem}
style={styles.listview}
/>
<ActionButton title="Add" onpress={() => { }} />
</View>
);
}
}
When I run the app in the simulator I get a warning message
AlertIOS.alert() with 4th "type" parameter is deprecated and will be removed. User AlertIOS.prompt instead.
Hello,
This example is great!
I can understand both works well Firebase and React Native.
This kind of simple example is useful to understand total system's total work.
I would like to modify ListItem to add some more items.
Title + Price + Store etc
Model of database should be changed to manage it.
To improve this example, some suggestion will be appreciated.
Like Title + Price + Store 3 items's extension example in react native code is enough.
If someone already get this work, please give me some point of thi extension?
Thanks
Shoji Itagaki
I believe this is an issue in React-Native's implementation of the binary upload, but I will start here since I am getting an error message back
error {"code":"storage/unknown","message":"Firebase Storage: An unknown error occurred, please check the error payload for server response.","serverResponse":"Multipart body does not contain 2 or 3 parts.","name":"FirebaseError"}
Code
var fileRef = firebase.storage().ref('images/sample-text')
var uploadTask = fileRef.put(new File(['this is a small amount of data'], 'sample-text.txt', { type: "text/plain" }), { type: "text/plain" });
uploadTask.on('state_changed', function (snapshot) {
console.log('state_changed', snapshot);
}, function (error) {
console.log("error", JSON.stringify(error));
}, function () {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
var downloadURL = uploadTask.snapshot.downloadURL;
})
I see the same issue on IOS/Android... goes into the Firebase source and then it is over...
BTW the code works in regular reactJS
See here... https://jsfiddle.net/Aaronksaunders/69z2wepo/48545/
I am getting this dex error after I tried out this firebase. No idea how to solve it.
"dependencies": { "react": "16.0.0-alpha.12", "react-native": "^0.47.2", "react-native-google-signin": "^0.11.0", "react-native-photo-view": "^1.4.0", "react-navigation": "1.0.0-beta.11", "react-native-firebase":"^11.2.0" },
`Dex: Error converting bytecode to dex:WithDexForDebug
Cause: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzbdq;
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzbdq;
at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:591)
at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:546)
at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:528)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:164)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:188)
at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:504)
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:334)
at com.android.dx.command.dexer.Main.run(Main.java:277)
at com.android.dx.command.dexer.Main.main(Main.java:245)
at com.android.dx.command.Main.main(Main.java:106)
:app:transformClassesWithDexForDebug FAILED
FAILURE: Build failed with an exception.
com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: java.lang.UnsupportedOperationException
firabse worked correctly and after 1-day did not work. I faced this problem there days ago.but it was done without any reason.
I having this problem again.
I don't know where is the problem from.pls, see my code.
import * as firebase from 'firebase';
// Initialize Firebase
const firebaseConfig = {
apiKey: "AIzaSyDYvQaRPag_1pvnBLkxWRQEAOjujYONYu8",
authDomain: "contactmanager-a73ef.firebaseapp.com",
databaseURL: "https://contactmanager-a73ef.firebaseio.com",
storageBucket: "",
};
const myFirebaseApp = firebase.initializeApp(firebaseConfig);
export default myFirebaseApp
import React, { Component } from 'react';
import { Text,TextInput, View , Button } from 'react-native';
import * as firebase from 'firebase';
import myFirebaseApp from './myFirebaseApp';
export default class AddNewContact extends Component {
constructor(props) {
super(props);
this.state = {
name:"",
email:"",
brief:""
}
this.itemsRef = this.GetRef().child('users');
}
GetRef() {
return myFirebaseApp.database().ref();
}
writeUserData(){
this.itemsRef.push({
username: this.state.name,
email: this.state.email,
brief : this.state.brief
}).then(()=>{
this.props.navigation.goBack(null)
});
}
SaveUser () {
this.itemsRef.push({
name: "user.name",
email: "user.email",
brief: "user.brief"
})
}
render() {
const navigation = this.props.navigation;
return (
<View>
<TextInput
style={{height: 40, borderWidth: 1}}
onChangeText={(text) => this.setState({name:text})}
value={this.state.name}
/>
<TextInput
style={{height: 40, borderWidth: 1}}
onChangeText={(text) => this.setState({email:text})}
value={this.state.email}
/>
<TextInput
style={{height: 40, borderWidth: 1}}
onChangeText={(text) => this.setState({brief:text})}
value={this.state.brief}
/>
<Button
onPress={()=>this.writeUserData()}
title="add"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
</View>
)
}
}
import React, { Component } from 'react';
import {
Platform,
ScrollView,
StyleSheet,
TouchableOpacity,
Text,
View,
Button,
FlatList
} from 'react-native';
import { SafeAreaView, StackNavigator } from 'react-navigation';
import AddNewContact from './components/AddNewContact';
import TodoList from './components/TodoList';
import myFirebaseApp from './components/myFirebaseApp';
class MainScreen extends Component {
constructor(props){
super(props);
this.state = {
users:""
};
this.itemsRef = this.getRef().child('users');
}
getRef() {
return myFirebaseApp.database().ref();
}
componentDidMount() {
this.itemsRef.on('value',(snap)=>{
console.log("snap"+snap);
// get children as an array
var items = [];
snap.forEach((child) => {
items.push({
username: child.val().username,
_key: child.key
});
});
this.setState({users:items});
console.log(items);
})
}
render() {
const navigation = this.props.navigation;
return(
<ScrollView style={{ flex: 1 }} contentInsetAdjustmentBehavior="automatic">
<View>
<FlatList
data= {this.state.users}
renderItem={({item}) => <Text>{item.username}</Text>}
/>
<Button
title="Add New Contact"
color="#841584"
accessibilityLabel="Learn more about this purple button"
onPress={()=>
navigation.navigate('AddNewContact',{name: 'AddNewContact'})
}
/>
</View>
</ScrollView>
)
}
}
const AppNavigator = StackNavigator(
{
AddNewContact:{
screen: AddNewContact
},
Index: {
screen: MainScreen,
},
},
{
initialRouteName: 'Index',
headerMode: 'none',
/*
* Use modal on iOS because the card mode comes from the right,
* which conflicts with the drawer example gesture
*/
mode: Platform.OS === 'ios' ? 'modal' : 'card',
}
);
export default AppNavigator
This is actually a question and not an issue, but hopefully one applicable to the broader community. This sample is awesome, but its built around the concept of a single page.
For apps that are going to access firebase from numerous views - login, account page, details page, etc - what is the Firebase team's recommendation on the best practice for storing the config and initializing the app? I can't imagine we would duplicate that code on every page looking to access Firebase.
Thanks!
The following commands produced analyzer issues:
Analyze Modules/RCTUIManager.m
(1 command with analyzer issues)
Should we just do this?
const React = require("react-native");
const firebase = require("firebase");
// Initialize Firebase
const firebaseConfig = {
apiKey: "<YOUR-API-KEY>",
authDomain: "<YOUR-AUTH-DOMAIN>",
databaseURL: "<YOUR-DATABASE-URL>",
storageBucket: "",
};
firebase.initializeApp(firebaseConfig);
// Create a reference with .ref() instead of new Firebase(url)
const rootRef = firebase.database().ref();
export default rootRef; // <<<<
assume we can just make this a module and initialize the db this way, but I am pretty new to Firebase
I see the example is only valid for iOS. Should I also make it workable for android?
Please add 3.x support to RN. My app red screens as soon as I call initializeApp
Hi Firebase.
I'm trying to integrate Firebase 3.1.0 with React Native 0.28.0.
I've implemented some codes that sign in with facebook, but it doesn't work with below error.
I debugged location.protocol
but it printed http:
.
This is snippet of my codes.
function logInWithFacebook(source:?string):ThunkAction {
return async dispatch => {
try {
console.log(location.protocol); // 'http:'
PROVIDERS.facebook.addScope('public_profile,email,user_friends');
const { user, credential } = await firebase.auth().signInWithPopup(new firebase.auth.FacebookAuthProvider());
return dispatch(login(user, credential, source));
} catch (error) {
const message = error.message || error;
alert(message);
console.warn(message);
}
};
}
Did I something wrong?
How could I fix this?
Thanks.
=== BUILD TARGET RCTLinking OF PROJECT RCTLinking WITH CONFIGURATION Debug ===
Check dependencies
=== BUILD TARGET RCTVibration OF PROJECT RCTVibration WITH CONFIGURATION Debug ===
Check dependencies
** BUILD FAILED **
The following build commands failed:
CompileC /Users/jrempel/WebstormProjects/firebase-react-native-sample/ios/build/Build/Intermediates/RCTWebSocket.build/Debug-iphonesimulator/RCTWebSocket.build/Objects-normal/x86_64/RCTSRWebSocket.o RCTSRWebSocket.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
(1 failure)
Installing build/Build/Products/Debug-iphonesimulator/FirebaseReactNativeSample.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist
(node:32368) [DEP0022] DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
/Users/jrempel/WebstormProjects/firebase-react-native-sample/node_modules/promise/lib/done.js:10
throw err;
^
Error: Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/FirebaseReactNativeSample.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist
at checkExecSyncError (child_process.js:588:13)
at Object.execFileSync (child_process.js:608:13)
at _runIOS (/Users/jrempel/WebstormProjects/firebase-react-native-sample/node_modules/react-native/local-cli/runIOS/runIOS.js:91:34)
at Promise (/Users/jrempel/WebstormProjects/firebase-react-native-sample/node_modules/react-native/local-cli/runIOS/runIOS.js:24:5)
at tryCallTwo (/Users/jrempel/WebstormProjects/firebase-react-native-sample/node_modules/promise/lib/core.js:45:5)
at doResolve (/Users/jrempel/WebstormProjects/firebase-react-native-sample/node_modules/promise/lib/core.js:200:13)
at new Promise (/Users/jrempel/WebstormProjects/firebase-react-native-sample/node_modules/promise/lib/core.js:66:3)
at Array.runIOS (/Users/jrempel/WebstormProjects/firebase-react-native-sample/node_modules/react-native/local-cli/runIOS/runIOS.js:23:10)
at Object.run (/Users/jrempel/WebstormProjects/firebase-react-native-sample/node_modules/react-native/local-cli/cliEntry.js:95:3)
at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:117:7)
The sample code in styles.js was cut and pasted into my react-native app for iOS with ES6 enabled in .babelrc. It resulted in a wasted afternoon of react-native redbox errors in my iphone simulator.
The issue traced right to the styles.js file from this project. I added a few missing semi-colon line terminations with one termination per line: EACH "const" declaration line, and one termation on the first "module.exports" assignment.
Sanity was restored as a result of those fixes. Admission: I lack [email protected] and JSX depth and understanding and probably misplaced my frustration entirely. This issue was opened to raise the question: are semi-colon line terminations missing or not?
If so, please update or caution us about styles.js. If not, please forgive my ignorance and excuse my blame shifting.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.