Unable to read data from Firebase Realtime Database in React Native - javascript

I am working on a simple React Native app to read and write data from a Firebase database. My read and write permissions in Firebase have been set to true:
{
"rules": {
".read": true,
".write": true,
}
}
Here are my relevant files:
App.js
import React from 'react'
import {View, StyleSheet, Button} from 'react-native'
import * as firebase from 'firebase'
import RootStackNavigator from './navigation/RootNavigation'
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
isLoadingComplete: false
}
var firebaseConfig = {
apiKey: "xxxxxxx",
authDomain: "testproject-9d0bc.firebaseapp.com",
databaseURL: "https://testproject-9d0bc-default-rtdb.firebaseio.com",
projectId: "testproject-9d0bc",
storageBucket: "testproject-9d0bc.appspot.com",
messagingSenderId: "1003049293166",
appId: "1:1003049293166:web:1df37fd6d181cf895cdd7f"
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
} else {
firebase.app()
}
}
render() {
return (
<View style={styles.container}>
<RootStackNavigator/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});
RootStackNavigation.js
import React from 'react';
import { createAppContainer, StackNavigator } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import HomeScreen from '../src/screens/HomeScreen';
const RootStackNavigator = createStackNavigator(
{
screen: HomeScreen
},
{
initialRouteName:"screen", // first component that should be displayed
defaultNavigationOptions: {
title: "App"
}
}
);
export default createAppContainer(RootStackNavigator)
HomeScreen.js
import React from "react";
import { Text, StyleSheet, View, Button, TouchableOpacity } from "react-native";
import * as firebase from "firebase";
const HomeScreen = (
props
) => {
function getData() {
firebase
.database()
.ref("people/")
.on("value", (snapshot) => {
const age = snapshot.val().age;
console.log("Age: " + age);
});
}
return (
<View>
<Text>Hello this is the home screen</Text>
<Button title="Get Data" onPress={getData} />
</View>
);
};
const styles = StyleSheet.create({
text: {
fontSize: 30,
},
});
export default HomeScreen;
My firebase database looks like this (all data was manually added through the firebase website)and I want to be able to print out these items after pressing the "Get Data" button to the console as shown in my getData function in HomeScreen.js
However, my code in getData does not work and nothing prints out to my console. What am I missing here?

Kindly modify this in your code
firebase.database.ref("people").on("value", snapshots => {
let peoples = [];
snapshots.forEach((snapshot) => {
peoples.push(snapshot.val().age);
console.log(snapshot.val().age);
});
// here you can set this Array
// setPeople(peoples)

Figured out my issue. As you can see in my firebase database, the way I was accessing my data was wrong. If I wanted to get the age of "dad", I should have called snapshot.val().dad.

Related

React Native app doesn't connect with Firebase anymore

I am facing an issue for the last 2 weeks. I was able to connect successfully my React Native app to Firebase and could see the details on the Firebase console. However, 2 weeks back the app suddenly stopped working. All I see now is a white screen. I am trying to capture Facebook Login through Firebase and tried removing firebase code and was successfully able to connect with the FB(So I guess the issue is with Firebase connection).
Any pointers will be highly appreciated.
Here is my code
App.js
import React from 'react';
import Login from './screens/Login';
import reducers from './redux/reducers';
import thunkMiddleware from 'redux-thunk';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
const middleware = applyMiddleware(thunkMiddleware)
const store = createStore(reducers, middleware);
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<Login/>
</Provider>
);
}
}
Login Screen
import React from 'react';
import styles from '../styles'
import NavigationContainer from '../navigation/RootNavigator';
import { connect } from 'react-redux';
import { login } from '../redux/actions'
import * as firebase from 'firebase';
import firebaseConfig from '../config/firebase.js'
import * as Facebook from 'expo-facebook';
firebase.initializeApp(firebaseConfig);
import {
Text,
View,
Alert,
TouchableOpacity
} from 'react-native';
class Login extends React.Component {
state = {}
UNSAFE_componentWillMount() {
firebase.auth().onAuthStateChanged((user) => {
if (user != null) {
this.props.dispatch(login(true))
console.log("We are authenticated now!" + JSON.stringify(user));
}
});
}
login = async () => {
try {
await Facebook.initializeAsync({
appId: '1742056282625463',
});
const {
type,
token,
} = await Facebook.logInWithReadPermissionsAsync({
permissions: ['public_profile'],
});
if (type === 'success') {
// Get the user's name using Facebook's Graph API
const response = await fetch(`https://graph.facebook.com/me?access_token=${token}`);
Alert.alert('Logged in!', `Hi ${(await response.json()).name}!`);
// Build Firebase credential with the Facebook access token.
const credential = await firebase.auth.FacebookAuthProvider.credential(token);
// Sign in with credential from the Facebook user.
firebase.auth().signInWithCredential(credential).catch((error) => {
// Handle Errors here.
Alert.alert("Try Again")
});
} else {
// type === 'cancel'
Alert.alert("Cancel")
}
} catch ({ message }) {
alert(`Facebook Login Error: ${message}`);
}
}
render() {
if(this.props.loggedIn){
return (
<NavigationContainer/>
)
} else {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.login.bind(this)}>
<Text>{this.props.loggedIn}</Text>
</TouchableOpacity>
</View>
)
}
}
}
function mapStateToProps(state) {
return {
loggedIn: state.loggedIn
};
}
export default connect(mapStateToProps)(Login);
Firebase
var firebaseConfig = {
apiKey: "AIzaSyCWjS5WxFgaBajsWKQPFLbC9QekmyxiO7I",
authDomain: "bookworm-d8e9f.firebaseapp.com",
databaseURL: "https://bookworm-d8e9f.firebaseio.com",
projectId: "bookworm-d8e9f",
storageBucket: "bookworm-d8e9f.appspot.com",
messagingSenderId: "1097080341399",
appId: "1:1097080341399:web:767ce9b106a13ae103bad2",
measurementId: "G-2JY9B79XCC"
};
// Initialize Firebase
//firebase.initializeApp(firebaseConfig);
//firebase.analytics();
module.exports = firebaseConfig
Redux - Action
export function login(input){
return function(dispatch){
dispatch({ type: 'LOGIN', payload: input });
}
}
Redux - Reducers
export default reducers = (state = {
loggedIn: false,
}, action) => {
switch (action.type) {
case 'LOGIN': {
return { ...state, loggedIn: action.payload }
}
}
return state;
}

Element type error on a firebase-React Native project

Im new at coding and am making a firebase-react native app. What I want to do know is the app to show users the login screen if they are not login yet and show the app screen if they are log in but when I try to run the app, it gives me the error shown in the image below. What Im doing wrong? Thank you.
/**
* #format
*/
import React, { Component } from 'react'
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator
} from 'react-native';
import {name as appName} from './app.json';
import App from './component/App'
import * as firebase from 'firebase'
import Login from './component/Login'
//import Firebase from './lib/Firebase'
const firebaseConfig = {
apiKey: "dhshdsjkfbsdjkvbjksdvbjksd",
authDomain: "dhshdsjkfbsdjkvbjksdvbjksd",
databaseURL: "dhshdsjkfbsdjkvbjksdvbjksd",
projectId: "dhshdsjkfbsdjkvbjksdvbjksd",
storageBucket: "dhshdsjkfbsdjkvbjksdvbjksd",
messagingSenderId: "dhshdsjkfbsdjkvbjksdvbjksd",
appId: "dhshdsjkfbsdjkvbjksdvbjksd",
measurementId: "dhshdsjkfbsdjkvbjksdvbjksd"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export default class dribbleAppUi1 extends Component {
constructor(props){
super(props)
this.state = {
initialView : null,
userLoaded: false
}
this.getInitialView()
this.getInitialView = this.getInitialView.bind(this)
}
getInitialView (){
firebase.auth().onAuthStateChanged((user) => {
let initialView = user ? 'App' : 'Login'
this.setState({
userLoaded: true,
initialView
})
})
}
configureScene(route) {
if(route.sceneConfig) {
return route.sceneConfig
} else {
return ({
...Navigator.sceneConfigs.HorizontalSwipeJumpFromRight,
gestures: {}
})
}
}
renderScene(route, navigator){
var globalProps = {navigator}
switch(route.id){
case 'App':
return (
<App navigator={navigator} />
)
case 'Login':
return (
<Login navigator={navigator} />
)
}
}
render() {
if(this.state.userLoaded) {
return (
<Navigator
initialRoute={{
id: this.state.initialView
}}
renderScene={this.renderScene}
configureScene={this.configureScene}
/>
);
}else {
return null
}
}
}
AppRegistry.registerComponent('Tiismo', () => dribbleAppUi1);
Im trying to make a project with firebase and react native. For now, Im trying to get users to login page if there are no login but I'm getting the error in the image below. What Im doing wrong? Thank You.
You cannot simply return null in render. Try this.
if(this.state.userLoaded) {
return (
<Navigator
initialRoute={{
id: this.state.initialView
}}
renderScene={this.renderScene}
configureScene={this.configureScene}
/>
);
}else {
return (<Text>Loading</Text>)
}

Undefined ' this.props.navigation.state.props.p' navigation react-native

I have read all the other topics about this issue, but no one is the solution to my problem.
I don't know why, but I can't pass props to react-navigation when I try to navigate, I always get this error:
"Undefined ' this.props.navigation.state.props.p'"
There is my code:
import React from 'react'
import {View, Text, ActivityIndicator, StyleSheet} from 'react-native'
import * as firebase from 'firebase';
const config = {
apiKey: "AIzaSyBeFuR40n7vp1XU9edL8PeOFq3UafKQ314",
authDomain: "anylibrary-961e1.firebaseapp.com",
databaseURL: "https://anylibrary-961e1.firebaseio.com",
projectId: "anylibrary-961e1",
storageBucket: "anylibrary-961e1.appspot.com",
messagingSenderId: "482573837189"
};
export default class Loading extends React.Component {
static navigationOptions = {
header: null,
};
constructor(props) {
super(props);
}
componentWillMount() {
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
}
componentDidMount() {
firebase.auth().onAuthStateChanged(user => {
const {navigate} = this.props.navigation;
if (user) {
navigate('UserArea', {p: 'Profile'});
} else {
navigate('MainPage');
}
})
}
render() {
return (
<View style={styles.container}>
<Text>Loading...</Text>
<ActivityIndicator size="large"/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
})
And:
import React from 'react';
import {StyleSheet, View, Alert} from 'react-native';
import Profile from './Profile';
import Notifications from './Notifications';
import Search from './Search';
import Home from './Home';
import Tabbar from 'react-native-tabbar-bottom'
import * as firebase from 'firebase';
const config = {
apiKey: "AIzaSyBeFuR40n7vp1XU9edL8PeOFq3UafKQ314",
authDomain: "anylibrary-961e1.firebaseapp.com",
databaseURL: "https://anylibrary-961e1.firebaseio.com",
projectId: "anylibrary-961e1",
storageBucket: "anylibrary-961e1.appspot.com",
messagingSenderId: "482573837189"
};
export default class UserArea extends React.Component {
static navigationOptions = {
header: null,
}
constructor(props) {
super(props);
this.state = {
page: this.props.navigation.state.props.p,
name: '',
}
}
componentWillMount(){
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
}
componentDidMount() {
firebase.auth().onAuthStateChanged(user => {
this.state.name = user.displayName;
})
}
render() {
return (
<View style={styles.container}>
{this.state.page === "Home" && <Home navigation={this.props.navigation}>Home</Home>}
{this.state.page === "Profile" && <Profile navigation={this.props.navigation}>Profile</Profile>}
{this.state.page === "Notifications" && <Notifications navigation={this.props.navigation}>Notifications</Notifications>}
{this.state.page === "Search" && <Search navigation={this.props.navigation}>Search</Search>}
<Tabbar
stateFunc={(tab) => {
this.setState({page: tab.page})
//this.props.navigation.setParams({tabTitle: tab.title})
}}
activePage={this.state.page}
tabbarBgColor='#00619A'
iconColor='#99c2ff'
tabs={[
{
page: "Home",
icon: "home",
iconText: "Home"
},
{
page: "Profile",
icon: "person",
iconText: "Profile"
},
{
page: "Notifications",
icon: "notifications",
badgeNumber: 0,
iconText: "Notifications"
},
{
page: "Search",
icon: "search",
iconText: "Search"
},
]}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
Basically i send it like that:
navigate('UserArea', {p: 'Profile'});
and try to acces it like that:
page: this.props.navigation.state.props.p,
Anyone?
Where is the problem?
What I am doing wrong?
from the documentation this looks like the correct way to get the route params
this.props.navigation.state.params.p
https://reactnavigation.org/docs/en/navigation-prop.html
old method is
this.props.navigation.state.params
new method is
this.props.route.params
im using rn version 0.62,
react navigation version -5
try this one:
page: this.props.navigation.state.p
i advise you to use getParam - Get a specific param value with a fallback
const name = this.props.navigation.getParam('name', 'Peter');
if name or param are undefined, set the fallback to Peter.
If using react-navigation v5, use
const data = route.params?.someParam ?? 'defaultValue';

Need to specify screen react native tabnavigator

Problem
I made a very basic app using React Native, and now I want to have multiple tabs. When I tried to add a feed and comments tab, I get an error saying:
Uncaught Error: Route 'Feed' should declare a screen.
For example:
import MyScreen from './MyScreen'
...
Feed: {
Screen: MyScreen,
}
I don't know why I am getting this error, since the first class I call is the 'App' screen, which is what I named the screen. I would love some help getting this tab error fixed. Thank you!
Code
import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, TextInput, ScrollView, TouchableHighlight, Button, FlatList } from 'react-native';
import { Font } from 'expo';
import * as firebase from 'firebase';
import { TabNavigator } from 'react-navigation';
const firebaseConfig = {
apiKey: "API-key",
authDomain: "candidtwo.firebaseapp.com",
databaseURL: "https://candidtwo.firebaseio.com",
storageBucket: "candidtwo.appspot.com",
};
const MyApp = TabNavigator({
Feed: {
screen: App,
},
CommentScreen: {
screen: Comments,
},
}, {
tabBarPosition: 'top',
animationEnabled: true,
tabBarOptions: {
activeTintColor: '#fe8200',
},
});
const firebaseApp = firebase.initializeApp(firebaseConfig);
var fontLoaded = false;
var ref = firebase.database().ref('posts');
var brightColor = ['#ffffff'];
var darkColor = ['#D3D3D3'];
var animalNames = ['WittyRhino','FriendlyRhino'];
var newPostRef = ref.push();
var postWidth = 360;
class App extends React.Component {
static navigationOptions = {
tabBarLabel: 'Home',
};
//App Code
}
class Comments extends React.Component {
static navigationOptions = {
tabBarLabel: 'Notifications',
};
render() {
return (
<Button
onPress={() => this.props.navigation.navigate('App')}
title="Go to notifications"
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 8,
backgroundColor: '#e8e8e8',
alignItems: 'center'
},
button: {
flex: 1,
backgroundColor: '#e8e8e8',
alignItems: 'center'
},
});
Define App and Comments components before
const MyApp = TabNavigator(...)
Hope this will help.

Data not inserting into Firebase Database

I am tring to insert a record from my react native app to Firebase.
And my code as follow:
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import * as firebase from 'firebase';
var React = require('react-native');
var {
Component,
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
TextInput,
ListView
} = React;
var Firebase = require('firebase');
export default class App extends React.Component {
constructor(props) {
super(props);
var myFirebaseRef = new Firebase('https://test.firebaseio.com/');
myFirebaseRef.set({
title: "Hello World!",
author: "Simon",
location: {
city: "Muenster",
state: "Germany",
zip: 48155
}
});
}
render() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
AppRegistry.registerComponent('devdacticFirebase', () => devdacticFirebase);
However, when I launch the app, the record is not inserting into my Firebase. It never throw me any error message also. Why is it so? Which part am I missing out?
You're mixing es5 & es6 code. Since you've already import firebase, you don't need to require it.
REFERENCE
In ES5, if you use CommonJS standard, the introduction of React package through basic require, the code is similar to this:
var ReactNative = require("react-native");
var {Image,Text} = ReactNative;
In ES6, the import wording is more standard similar to this:
import { Image, Text} from 'react-native'
Recently firebase has updated their web SDK, which changed some of its API. The syntax you're using looks like the 2.x API, while the latest version is pretty different
Please initialize the firebase once the app is loaded (recommend in componentWillMount method) so that you can use it everywhere in the code
componentWillMount() {
var config = {
"apiKey": "YOUR_API_KEY",
"authDomain": "YOUR_FB_DOMAIN",
"databaseURL": "YOUR_FIREBASE_URL",
"projectId": "YOUR_FB_PROJECT_ID"
}
firebase.initializeApp(config);
}
UPDATE
It is weird when you put firebase set in the constructor. I guess you want to add new record to the firebase, you can use set with push(), this will add new record. Let say you have user table in the database, so :
import {TouchableOpacity} from 'react-native';
export default class App extends React.Component {
componentWillMount() {
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "..."
};
firebase.initializeApp(config);
}
constructor(props) {
super(props);
}
insert = () => {
firebase.database().ref('user').push().set({
title: "Hello World!",
author: "Simon",
location: "Germany",
city: "Muenster",
state: "Germany",
zip: 48155
}, (error) => {
if (error) {
console.log(error.message);
} else {
// Success
}
});
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={()=> this.insert()}>
<Text>Hello World!</Text>
</TouchableOpacity>
</View>
);
}
}

Categories

Resources