Problem in rendering from firebase-React-Native - firebase

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}

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

Could anyone help me to write code to upload image to the firestore database with url below is my code to upload image with form

I couldn't find a way to upload image to the firestore database with url while I am submitting the I am getting the file path like file:///data/user/0/com.kk/cache/rn_image_picker_lib_temp_6e973dbe-ab8f, but I need to get file path with url in firestore. Could anyone help with this?. Below is my code to upload image with form.
import React, { useState } from "react";
import { View,StyleSheet,Text, ScrollView, Pressable, Image, TextInput } from 'react-native';
import { Button } from "react-native-elements";
import {firebase} from '#react-native-firebase/firestore';
import { launchImageLibrary } from "react-native-image-picker";
export default function Test(){
const [username,setusername] = useState('');
const [email,setemail] = useState('');
const[imageURI,setImageURI] = useState(null);
const handleOpenLibrary = async () => {
let options = {
mediaType: "photo",
};
const imageData = await launchImageLibrary(options);
setImageURI(imageData.assets[0].uri);
};
function create(){
firebase.firestore()
.collection('Actors')
.add({
name: username,
email: email,
image: {uri:imageURI},
}).then(() => {
console.log("data submitted");
}).catch((error)=> {
console.log(error);
});;
} return (
<View style={styles.body}>
<View style={styles.row}>
<TextInput
style={{backgroundColor:'white'}}
value={username}
onChangeText= {(username) => {setusername(username)}}
placeholder="Enter name"/>
</View>
<View style={styles.row}>
<TextInput
style={{backgroundColor:'white'}}
value={email}
onChangeText= {(email) => {setemail(email)}}
placeholder="Enter email"/>
</View>
<View style={styles.imageContainer}>
<Image
source={{uri:imageURI}}
style={styles.imageBox}
resizeMode='contain'
/>
</View>
<Button
title="submit"
onPress={create}/>
<Button title="pick" onPress={handleOpenLibrary}/>
</View>
)}
const styles = StyleSheet.create({
body: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'black',
alignItems: 'center',
justifyContent: 'flex-start',
},
text: {
fontSize: 40,
margin: 10,
},
row: {
flexDirection: 'row',
alignItems: 'flex-start',
justifyContent:'space-between',
},
footer: {
position: 'absolute',
flex:0.1,
left: 0,
right: 0,
bottom: -10,
flexDirection:'row',
height:50,
alignItems:'center',
justifyContent:'center',
borderRadius:10,
},
footerText: {
color:'white',
fontWeight:'bold',
alignItems:'center',
fontSize:18,
},
imageContainer: {
marginVertical: 20,
borderWidth: 5,
borderColor: '#ff5555'
},
imageBox: {
width: 256,
height: 256
}
});

sum items of Flatlist on react native

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

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 to use fetch with wordpress rest API

I have this code and I wanna login using the link in the fetch of this below code but I'm getting this error while clicking on the login button: JSON Parse Error: Unexpected EOF. I'm trying to use rest API for this login app.
var React = require('react');
var ReactNative = require('react-native');
var t = require('tcomb-form-native');
var {
AppRegistry,
AsyncStorage,
StyleSheet,
Text,
View,
TouchableHighlight,
AlertIOS,
Image,
} = ReactNative;
var STORAGE_KEY = 'id_token';
var Form = t.form.Form;
var Person = t.struct({
username: t.String,
password: t.String
});
const options = {};
var AwesomeProject = React.createClass({
async _onValueChange(item, selectedValue) {
try {
await AsyncStorage.setItem(item, selectedValue);
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
},
componentDidMount: function() {
this._userLogin();
},
_userLogin: function() {
var value = this.refs.form.getValue();
if (value) { // if validation fails, value will be null
fetch("http://vowelserver.com/trades/test_autheticate/", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: value.username,
password: value.password,
})
}).then((response) => response.json())
.then((responseData) => {
this._onValueChange(STORAGE_KEY, responseData.id_token)
}).done();
}
},
render() {
return (
<View style={styles.container}>
<View style={styles.container}>
<Image
resizeMode="contain"
source={{uri: 'http://res.cloudinary.com/vowelweb/image/upload/v1498114115/Logo_mqzlgt.png'}}
style={styles.image}
/>
</View>
<View style={styles.row}>
<Form
ref="form"
type={Person}
options={options}
/>
</View>
<View style={styles.row}>
<TouchableHighlight style={styles.button} onPress={this._userLogin} underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Login</Text>
</TouchableHighlight>
</View>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
justifyContent: 'center',
marginTop: 50,
padding: 20,
backgroundColor: '#ffffff',
},
containers: {
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
backgroundColor: 'white',
position: 'relative',
borderBottomWidth: 1,
},
title: {
fontSize: 30,
alignSelf: 'center',
marginBottom: 30
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
button: {
height: 36,
backgroundColor: '#48BBEC',
borderColor: '#48BBEC',
borderWidth: 1,
borderRadius: 8,
marginBottom: 10,
alignSelf: 'stretch',
justifyContent: 'center'
},
login: {
flex: 1,
backgroundColor: '#efeff2',
alignItems: 'center',
justifyContent: 'center',
},
image: {
position: 'absolute',
top: 0,
bottom: 0,
left: 30,`enter code here`
right: 30,
},
});
AppRegistry.registerComponent('FirstRun', () => AwesomeProject);
This line...
(response) => response.json()
assumes that you are getting a string that is parseable into JSON.
Try inspecting the response.
Pleas find the code snippet for the simple fetch api call in react.make sure you have valid url which will return you the response
getMoviesFromApiAsync = () => {
return fetch('http://droidtute.com/reactexample/sample_api/getMovieList.php')
.then((response) => response.json())
.then((responseJson) => {
// alert(JSON.stringify(responseJson))
this.setState({ moviesList: responseJson.movieList }) // this will update state to re-render ui
return responseJson.movieList;
})
.catch((error) => {
console.error(error);
});
}

Resources