Coder Social home page Coder Social logo

firebase-react-native-sample's People

Contributors

davideast avatar drmas avatar laiso avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-react-native-sample's Issues

Disk Persistence capability in react-native

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!

redux integration ?

I think is it valuable to consider how to integrate redux with firebase instead query in container directly.

Firebase constructor

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

[Google] auth/operation-not-supported-in-this-environment

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);
  })

Aditional Information:

"firebase": "^3.7.1",
"react-native": "^0.42.0",
platform: Android

any ideas?
thanks in advance!

Example: Authentication with Google

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

Android Working?

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?

errors on ios trying to build

screenshot 2016-10-01 15 52 16

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/>

[Google] signInWithCredential: auth/internal-error

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

Authorization Example since 3.1?

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.

Using ComponentWillMount instead of ComponentDidMount ?

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 !!

undefined is not an object (evaluating 'itemsRef.on')

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>
        );
    }
}

ListItem extension?

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

File Storage Doesn't Work w/React Native

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/

Compilation error

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.

  • What went wrong:
    Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: java.lang.UnsupportedOperationException

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
    BUILD FAILED`

same times firebase not work!!!!

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

and complete source

Best practice for storing and accessing Firebase config across entire app

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!

Analyzer issue

The following commands produced analyzer issues:
Analyze Modules/RCTUIManager.m
(1 command with analyzer issues)

initializing the db

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

`auth().signInWithPopup()` is not working in React Native

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.

2016-07-17 9 22 37

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.

Project build fails

=== 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)

Are semi-colon terminations missing on some lines?

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.