sum items of Flatlist on react native - sqlite

I'm making an app that makes a bill of items and the user can identify the quantity of every item
and at least there is a text tag which it shows the total price after hitting " get bill " button
it works fine , but the issue is after hitting the button the items are repeated again
[here a screenshot of the app after hitting a 'get bill' button]: https://i.stack.imgur.com/slOWN.jpg
this is the code :
import React, { Component } from "react";
import { View, FlatList, Dimensions, Text } from "react-native";
import * as SQLite from "expo-sqlite";
import { Button } from "react-native-elements";
import NumericInput from "react-native-numeric-input";
const db = SQLite.openDatabase("db.db");
class CreateBill extends Component {
constructor() {
super();
this.state = {
items: [],
itemsList: [],
products: [],
totalPrice: 0,
};
}
async componentDidMount() {
console.log("did mount");
db.transaction((tx) => {
tx.executeSql("SELECT * FROM products2", [], (tx, results) => {
var temp = [];
for (let i = 0; i < results.rows.length; ++i) {
temp.push(results.rows.item(i));
}
this.setState({
products: temp,
});
});
});
}
checkItems = () => {
this.state.items.forEach((item) => {
this.state.products.forEach((product) => {
if (item === product.code) {
console.log("equals", item, product.code);
this.state.itemsList.push({ product, number: 0 });
} else {
console.log("doesnt equal", item.item, product.code);
}
});
});
};
getPrice = () => {
let price = 0;
this.state.itemsList.forEach((element) => {
price = element.number * element.product.price;
});
this.setState({ totalPrice: price });
};
render() {
this.state.items = this.props.route.params.items;
this.checkItems();
return (
<View style={{ flex: 1 }}>
<FlatList
data={this.state.itemsList}
extraData={this.state}
style={{ marginTop: 50, flex: 1, width: Dimensions.width }}
keyExtractor={(item) => item.product.id}
renderSeparator={() => (
<View
style={{
backgroundColor: "#1B73B4",
height: 0.6,
}}
/>
)}
renderItem={({ item, index }) => {
console.log("item", item);
return (
<View
style={{
flexDirection: "row",
width: Dimensions.width,
paddingStart: 20,
alignItems: "center",
}}
key={item}
>
<View style={{ flex: 0.5, alignItems: "center" }}>
<Text style={{ fontSize: 24 }}>{item.product.name}</Text>
</View>
<View style={{ flex: 0.5, justifyContent: "center" }}>
<NumericInput
value={this.state.itemsList[index].number}
onChange={(value) => {
let item1 = this.state.itemsList[index];
item1.number = value;
console.log(
this.state.itemsList[index].product.name,
this.state.itemsList[index].number
);
}}
totalWidth={140}
totalHeight={45}
iconSize={25}
maxValue={this.state.itemsList[index].product.units}
minValue={0}
valueType="integer"
rounded
textColor="#1B73B4"
iconStyle={{ color: "white" }}
rightButtonBackgroundColor="#1B73B4"
leftButtonBackgroundColor="#1B73B4"
/>
</View>
</View>
);
}}
/>
<Text>{this.state.totalPrice}</Text>
<Button title="get bill" onPress={() => this.getPrice()} />
</View>
);
}
}
export { CreateBill };

In your case reduce is the best option:
Documentation here
Example:
const totalPrice = this.state.itemsList.reduce((total, element) =>
total += element.number * element.product.price
,0);
this.setState({ totalPrice });

Related

react native. how to make the left side non scrollable at table below

so I have a question/answer table below and I want to make the left part of the table to stick there. Each row is mapped individually(1st row- title, than the radio buttons for that, 2nd row than the buttons and so on. in reactJs I would put a position sticky or fixed to solve the problem but i dont know how to solve it in native.
a snack environment if anyone needs it https://snack.expo.dev/Mz0nR6Fj5
Here is the code
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, ScrollView } from 'react-native';
import Constants from 'expo-constants';
import { Button, RadioButton } from 'react-native-paper';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default function App() {
const [res, setRes] = useState([]);
let answers = ['good', ' bad', 'ehh'];
let question = [
'how are you',
'how the weather',
'how was the day',
'what do you think about ....',
];
useEffect(() => {
setRes(
question.map((title) => ({
title,
...answers.reduce((p, c) => ((p[c] = 0), p), {}),
}))
);
}, []);
const handleClick = (i, x) => {
setRes(
res.map((data) => {
if (i.title === data.title && i[x] === 0) {
const title = i.title;
for (const property in i) {
i[property] = 0;
}
i[x] = 1;
i.title = title;
}
// else if (i.title === data.title && i[x] === 1) {
// i[x] = 0;
// }
return data;
})
);
const yy = [];
console.log(res);
res.map(({ title, ...i }) => {
yy.push(Object.values(i).flat());
});
console.log(yy);
};
const show = () => {
const yy = [];
console.log(res);
res.map(({ title, ...i }) => {
yy.push(Object.values(i).flat());
});
console.log(yy);
// console.log(result);
// console.log('njeDheZero___ ', njeDheZero);
};
// console.table(players);
return (
<View>
<ScrollView horizontal={true} style={styles.container}>
<View
style={{
backgroundColor: 'white',
flexDirection: 'column',
borderTopWidth: 1,
borderLeftWidth: 1,
borderColor: '#ccc',
marginRight: 30,
}}>
<View style={{ flexDirection: 'row' }}>
<View
style={{
borderBottomWidth: 1,
borderRightWidth: 1,
borderColor: '#ccc',
width: 200,
}}>
<Text style={{ padding: 10 }}>-</Text>
</View>
{answers.map((subq) => (
<View
key={subq}
style={{
borderBottomWidth: 1,
borderRightWidth: 1,
borderColor: '#ccc',
width: 120,
}}>
<Text style={{ padding: 10 }}>{subq}</Text>
</View>
))}
</View>
{res.length > 0 ? (
<>
{res.map((i, inda) => {
// console.log("render",i.title)
return (
<View key={inda} style={{ flexDirection: 'row' }}>
<View
style={{
borderBottomWidth: 1,
borderRightWidth: 1,
borderColor: '#ccc',
width: 200,
}}>
<Text style={{ padding: 10 }}>{i?.title}</Text>
</View>
{answers.map((x, indq) => {
return (
<View
style={{
borderBottomWidth: 1,
borderRightWidth: 1,
borderColor: '#ccc',
width: 120,
justifyContent: 'center',
alignItems: 'center',
}}>
<RadioButton.Group>
<RadioButton
// value={i[x]}
status={i[x] === 1 ? 'checked' : 'unchecked'}
onPress={() => {
handleClick(i, x);
}}
/>
</RadioButton.Group>
</View>
);
})}
</View>
);
})}
</>
) : (
<Text>LOADING</Text>
)}
</View>
</ScrollView>
<Button onPress={show}>
<Text>SHOW</Text>
</Button>
</View>
);
}
const styles = StyleSheet.create({
// container: {
// flex: 1,
// justifyContent: 'center',
// paddingTop: Constants.statusBarHeight,
// backgroundColor: '#ecf0f1',
// padding: 8,
// },
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});

Problem in rendering from firebase-React-Native

I have this problem:
I have to render a FlatList mapping Firestore documents and I do like this:
componentDidMount();
{
const cat = [];
var db = firebase.firestore();
const ristoDoc = db.collection("ristoranti").where("telefono", "==", "3296812820");
ristoDoc.get().then((snapshot) => {
snapshot.forEach((doc) => {
this.setState({
id: doc.id,
});
});
});
db.collection("ristoranti")
.doc(this.state.id)
.collection("categorie")
.onSnapshot((querysnapshot) => {
querysnapshot.forEach((doc) => {
const data = doc.data();
this.setState({
nome: data,
});
cat.push(data);
});
this.setState({
categorie: cat,
});
});
}
And my FlatList:
<
FlatList horizontal = {
true
}
pagingEnabled = {
true
}
style = {
{
width: '100%',
height: '22%'
}
}
contentContainerStyle = {
{
height: '90%',
width: 100
}
}
data = {
this.state.categorie
}
renderItem = {
(item) =>
{
<View>
> <Text key={item.id}> {item.nome} </Text>
<View>
<TouchableOpacity onPress = {
() => this.setState(
{
visibileProdottoAdd: true
})
}>
<Text> + </Text> </TouchableOpacity> </View> </View>
But I have always the same error of the image []
I try all the day and nothing was changed I done a little error at item.name that a have curly braces in original code
Update
<FlatList
horizontal={true}
pagingEnabled={true}
style={{ width: "100%", height: "22%" }}
contentContainerStyle={{ height: "90%", width: 100 }}
data={this.state.categorie}
key={({ item }) => {
item.id;
}}
renderItem={({ item }) => {
<View
style={{
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
width: 200,
}}
>
<Text
key={item.id}
style={{
fontSize: 20,
color: "#C6C6C6",
marginBottom: 5,
width: "35%",
}}
>
{item.nome}
</Text>
<View
style={{
flexDirection: "row",
justifyContent: "flex-end",
alignItems: "center",
width: "60%",
}}
>
<TouchableOpacity
onPress={() =>
this.setState({ visibileProdottoAdd: true })
}
>
<Text style={{ fontSize: 20, color: "#66a3ff" }}>
+
</Text>
</TouchableOpacity>
</View>
</View>;
}}
></FlatList>
I edit my code in this version e nothing change, in componentdidmount function I try to test what was get from Firestore
componentDidMount() {
const cat = [];
var db = firebase.firestore();
const ristoDoc = db
.collection("ristoranti")
.where("telefono", "==", "3296812820");
ristoDoc.get().then((snapshot) => {
snapshot.forEach((doc) => {
this.setState({ id: doc.id });
});
});
db.collection("ristoranti")
.doc("qKEWUfZPsy2pu6IoFUio")
.collection("categorie")
.onSnapshot((querysnapshot) => {
querysnapshot.forEach((doc) => {
const data = doc.data();
this.setState({ nome: data });
cat.push(data);
cat.forEach(({i})=>{console.log(i.nome)})
});
this.setState({ categorie: cat });
});
The strange thing that it was an error on Expo Cli but in my Visual Studio console log i have my list of name.
You are doing a very simple mistake. I think Problem is in Render Item.
<FlatList
data={arr}
key={({ item }) => item}
onEndReached={({ index }) => handleLoadMore(index)}
renderItem={({item} ) => <RenderItem item={item} />}
/>
you are passing an item. you have to pass object {item}

TypeError: navigation.getParam is not a function - react native

This is the error I get-->
I have a HomeFeed.js where I list all my articles and when you click on each article you get taken to the Content.js where you can see the article details/content.
In the HomeFeed.js, when you press on the article this happens-->
..........................................................................................................................................................................................................................................................................................................................................................................................
onPress={() => {
this.props.navigation.navigate("Content", {
articlekey: `${JSON.stringify(item.key)}`,
});
}}
..........................................................................................................................................................................................................................................................................................................................................................................................
In my Content.js, I have the below:
import React, { Component } from "react";
import { StyleSheet, ScrollView, ActivityIndicator, View } from "react-native";
import { Text, Card } from "react-native-elements";
import firebase from "../../firebase";
class Content extends Component {
static navigationOptions = {
title: "Content",
};
constructor() {
super();
this.state = {
isLoading: true,
article: {},
key: "",
};
}
componentDidMount() {
const { navigation } = this.props;
const ref = firebase
.firestore()
.collection("articles")
.doc(JSON.parse(navigation.getParam("articlekey")));
ref.get().then((doc) => {
if (doc.exists) {
this.setState({
article: doc.data(),
key: doc.id,
isLoading: false,
});
} else {
console.log("No such document!");
}
});
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.activity}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
);
}
return (
<ScrollView>
<Card style={styles.container}>
<View style={styles.subContainer}>
<View>
<Text h3>{this.state.article.title}</Text>
</View>
<View>
<Text h5>{this.state.article.content}</Text>
</View>
</View>
</Card>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
subContainer: {
flex: 1,
paddingBottom: 20,
borderBottomWidth: 2,
borderBottomColor: "#CCCCCC",
},
activity: {
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: "center",
justifyContent: "center",
},
detailButton: {
marginTop: 10,
},
});
export default Content;
The problem is with your get method of parameters. With react-navigation version 5.X or upper, you need to get params with route.
SOLUTION
Change componentDidMount( ) like this
componentDidMount() {
// const { navigation } = this.props; remove this
const { articlekey } = this.props.route.params; //add this
const ref = firebase
.firestore()
.collection("articles")
.doc(JSON.parse(articlekey));
ref.get().then((doc) => {
if (doc.exists) {
this.setState({
article: doc.data(),
key: doc.id,
isLoading: false,
});
} else {
console.log("No such document!");
}
});
}

Advice need for React Navigation auth flow structure

Trying out react navigation v5 so I created a login register form that brings the user to the dashboard if he's logged in before using AsyncStorage. It works fine but I would like to know how to improve on the structure of code. Currently, I put all the components in a stack navigator, but things might get messy if I were to add more screens. Also, I would be switching to hooks but am confused if and how I should apply useContext useMemo useEffect
App.js file
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import Login from './components/login';
import Signup from './components/signup';
import Dashboard from './components/dashboard';
import AuthLoading from './components/authLoading'
const Stack = createStackNavigator();
function MyStack() {
return (
<Stack.Navigator
initialRouteName="AuthLoading"
screenOptions={{
headerTitleAlign: 'center',
headerStyle: {
backgroundColor: '#3740FE',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
}}>
<Stack.Screen
name="AuthLoading"
component={AuthLoading}
options={
{title: 'AuthLoading'},
{headerLeft:null}
}/>
<Stack.Screen
name="Signup"
component={Signup}
options={{ title: 'Signup' }}
/>
<Stack.Screen
name="Login"
component={Login}
options={
{ title: 'Login' },
{ headerLeft: null }
}
/>
<Stack.Screen
name="Dashboard"
component={Dashboard}
options={
{ title: 'Dashboard' },
{ headerLeft: null }
}
/>
</Stack.Navigator>
);
}
export default function App() {
return (
<NavigationContainer>
<MyStack />
</NavigationContainer>
);
}
authLoading.js file
import React from 'react';
import { ActivityIndicator, StatusBar, StyleSheet, View, Text } from 'react-native';
import {AsyncStorage} from 'react-native'
export default class AuthLoadingScreen extends React.Component {
constructor(props) {
super(props);
this.checkUserToken();
}
async checkUserToken() {
const isLoggedIn = await AsyncStorage.getItem('isLoggedIn');
console.log(isLoggedIn)
// If User Token
if (isLoggedIn === '1') {
//AsyncStorage.setItem(isLoggedIn);
this.props.navigation.navigate('Dashboard');
}
else {
this.props.navigation.navigate('Login');
}
}
// Render any loading content that you like here
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>Checking Authentication</Text>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
// Styles
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#CA3433',
justifyContent: 'center',
alignItems: 'center',
},
text: {
justifyContent: 'center',
color: '#fff',
fontSize: 18,
fontWeight: '500',
},
});
signup.js file
import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, Button, Alert, ActivityIndicator } from 'react-native';
import firebase from '../database/firebase';
export default class Signup extends Component {
constructor() {
super();
this.state = {
displayName: '',
email: '',
password: '',
isLoading: false
}
}
updateInputVal = (val, prop) => {
const state = this.state;
state[prop] = val;
this.setState(state);
}
registerUser = () => {
if (this.state.email === '' && this.state.password === '') {
Alert.alert('Enter details to signup!')
} else {
this.setState({
isLoading: true,
})
firebase
.auth()
.createUserWithEmailAndPassword(this.state.email, this.state.password)
.then((res) => {
res.user.updateProfile({
displayName: this.state.displayName
})
console.log('User registered successfully!')
this.setState({
isLoading: false,
displayName: '',
email: '',
password: ''
})
this.props.navigation.navigate('Login')
})
.catch(error => this.setState({
isLoading: false,
errorMessage: error.message
}))
}
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.preloader}>
<ActivityIndicator size="large" color="#9E9E9E" />
</View>
)
}
return (
<View style={styles.container}>
<TextInput
style={styles.inputStyle}
placeholder="Name"
value={this.state.displayName}
onChangeText={(val) => this.updateInputVal(val, 'displayName')}
/>
<TextInput
style={styles.inputStyle}
placeholder="Email"
value={this.state.email}
onChangeText={(val) => this.updateInputVal(val, 'email')}
/>
<TextInput
style={styles.inputStyle}
placeholder="Password"
value={this.state.password}
onChangeText={(val) => this.updateInputVal(val, 'password')}
maxLength={15}
secureTextEntry={true}
/>
<Button
color="#3740FE"
title="Signup"
onPress={() => this.registerUser()}
/>
<Text>{this.state.errorMessage}</Text>
<Text
style={styles.loginText}
onPress={() => this.props.navigation.navigate('Login')}>
Already Registered? Click here to login
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
display: "flex",
flexDirection: "column",
justifyContent: "center",
padding: 35,
backgroundColor: '#fff'
},
inputStyle: {
width: '100%',
marginBottom: 15,
paddingBottom: 15,
alignSelf: "center",
borderColor: "#ccc",
borderBottomWidth: 1
},
loginText: {
color: '#3740FE',
marginTop: 25,
textAlign: 'center'
},
preloader: {
left: 0,
right: 0,
top: 0,
bottom: 0,
position: 'absolute',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#fff'
}
});
login.js file
import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, Button, Alert, ActivityIndicator } from 'react-native';
import firebase from '../database/firebase';
import {AsyncStorage} from 'react-native';
export default class Login extends Component {
constructor() {
super();
this.state = {
email: '',
password: '',
isLoading: false,
errorMessage: ''
}
}
updateInputVal = (val, prop) => {
const state = this.state;
state[prop] = val;
this.setState(state);
}
/**
*
*/
userLogin = () => {
if (this.state.email === '' && this.state.password === '') {
this.setState({
errorMessage: "Enter details to sign in"
})
//Alert.alert('Enter details to signin!')
} else {
this.setState({
isLoading: true,
})
firebase
.auth()
.signInWithEmailAndPassword(this.state.email, this.state.password)
.then((res) => {
console.log(res)
console.log('User logged-in successfully!')
this.setState({
isLoading: false,
email: '',
password: ''
})
AsyncStorage.setItem('isLoggedIn', '1')
this.props.navigation.navigate('Dashboard')
})
.catch(error => this.setState({
errorMessage: 'Wrong email/password',
isLoading: false
}))
}
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.preloader}>
<ActivityIndicator size="large" color="#9E9E9E" />
</View>
)
}
return (
<View style={styles.container}>
<TextInput
style={styles.inputStyle}
placeholder="Email"
value={this.state.email}
onChangeText={(val) => this.updateInputVal(val, 'email')}
/>
<TextInput
style={styles.inputStyle}
placeholder="Password"
value={this.state.password}
onChangeText={(val) => this.updateInputVal(val, 'password')}
maxLength={15}
secureTextEntry={true}
/>
<Button
color="#3740FE"
title="Signin"
onPress={() => this.userLogin()}
/>
{/* style this */}
<Text>{this.state.errorMessage}</Text>
<Text
style={styles.loginText}
onPress={() => this.props.navigation.navigate('Signup')}>
Don't have account? Click here to signup
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
display: "flex",
flexDirection: "column",
justifyContent: "center",
padding: 35,
backgroundColor: '#fff'
},
inputStyle: {
width: '100%',
marginBottom: 15,
paddingBottom: 15,
alignSelf: "center",
borderColor: "#ccc",
borderBottomWidth: 1
},
loginText: {
color: '#3740FE',
marginTop: 25,
textAlign: 'center'
},
preloader: {
left: 0,
right: 0,
top: 0,
bottom: 0,
position: 'absolute',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#fff'
}
});
dashboard.js file
import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, Button, Alert, ActivityIndicator } from 'react-native';
import firebase from '../database/firebase';
import {AsyncStorage} from 'react-native';
export default class Login extends Component {
constructor() {
super();
this.state = {
email: '',
password: '',
isLoading: false,
errorMessage: ''
}
}
updateInputVal = (val, prop) => {
const state = this.state;
state[prop] = val;
this.setState(state);
}
/**
*
*/
userLogin = () => {
if (this.state.email === '' && this.state.password === '') {
this.setState({
errorMessage: "Enter details to sign in"
})
//Alert.alert('Enter details to signin!')
} else {
this.setState({
isLoading: true,
})
firebase
.auth()
.signInWithEmailAndPassword(this.state.email, this.state.password)
.then((res) => {
console.log(res)
console.log('User logged-in successfully!')
this.setState({
isLoading: false,
email: '',
password: ''
})
AsyncStorage.setItem('isLoggedIn', '1')
this.props.navigation.navigate('Dashboard')
})
.catch(error => this.setState({
errorMessage: 'Wrong email/password',
isLoading: false
}))
}
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.preloader}>
<ActivityIndicator size="large" color="#9E9E9E" />
</View>
)
}
return (
<View style={styles.container}>
<TextInput
style={styles.inputStyle}
placeholder="Email"
value={this.state.email}
onChangeText={(val) => this.updateInputVal(val, 'email')}
/>
<TextInput
style={styles.inputStyle}
placeholder="Password"
value={this.state.password}
onChangeText={(val) => this.updateInputVal(val, 'password')}
maxLength={15}
secureTextEntry={true}
/>
<Button
color="#3740FE"
title="Signin"
onPress={() => this.userLogin()}
/>
{/* style this */}
<Text>{this.state.errorMessage}</Text>
<Text
style={styles.loginText}
onPress={() => this.props.navigation.navigate('Signup')}>
Don't have account? Click here to signup
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
display: "flex",
flexDirection: "column",
justifyContent: "center",
padding: 35,
backgroundColor: '#fff'
},
inputStyle: {
width: '100%',
marginBottom: 15,
paddingBottom: 15,
alignSelf: "center",
borderColor: "#ccc",
borderBottomWidth: 1
},
loginText: {
color: '#3740FE',
marginTop: 25,
textAlign: 'center'
},
preloader: {
left: 0,
right: 0,
top: 0,
bottom: 0,
position: 'absolute',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#fff'
}
});
React-Navigation provided help regarding the auth flow on their official site. Just follow the below link
https://reactnavigation.org/docs/auth-flow/
Note: You can follow this article for authentication flow using hooks and react-navigation 5
https://dev.to/embeddednature/create-an-authorization-flow-with-react-navigation-5-x-2pkh

how you hide uids in firebase in react native?

i want hide the uids from displaying on my display page, right now it displays -LrM8rlKq1-dSW6XRt0_({"color: 'blue"}), but i just want it to display ({"color: 'blue"}) without uid(-LrM8rlKq1-dSW6XRt0_) beside it enter image description here
enter image description here
import React, { Component } from 'react';
import { View, Text, StyleSheet, Button, TextInput, TouchableOpacity } from 'react-native';
import firebase from './firebase';
export default class App extends Component {
carDatabase = firebase.database().ref('car');
state = { cars: {}, selectedId: '' }
// Read
componentDidMount() {
this.carDatabase.on('value', cars => {
const carsJSON = cars.val();
this.setState({ cars: carsJSON === null ? {} : carsJSON });
})
// this.carDatabase.push({color: 'yellow'})
}
// Create
create() {
this.carDatabase.push({color: 'yellow'})
this.setState({selectedId: ''})
}
// Update
update() {
this.carDatabase.child(this.state.selectedId).set({color: 'blue'})
this.setState({selectedId: ''})
}
// Delete
deleteCar() {
if(this.state.selectedId === '') {
return;
}
this.carDatabase.child(this.state.selectedId).set(null)
this.setState({selectedId: ''})
}
render() {
return (
<View style={styles.container}>
<TextInput value={this.state.selectedId} style={styles.textInput}></TextInput>
<Button title="create" onPress={() => this.create()}></Button>
<Button title="update" onPress={() => this.update()}></Button>
<Button title="delete" onPress={() => this.deleteCar()}></Button>
{
Object.keys(this.state.cars).map( (carId, index) => (
<Text style={{color: this.state.cars[carId].color}}>hi !</Text>
)
}
{/* <Text>{JSON.stringify(this.state.cars, null, 2)}</Text> */}
</View>
);
}
}
const styles = StyleSheet.create({
textInput: {
backgroundColor: 'green',
height: 30,
width: '100%'
},
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
});

Resources