POST data request on server via react native? - react-native

Basically what i'm trying to do is, on click of login button it should take my input data and check whether the data is valid for authentication and send back response to user and display on UI. After authentication it should be redirected to home screen. I tried using fetch but it's not working. Below is the code:
import React, { Component } from 'react';
import {
AppRegistry,
Text,
Image,
View,
StyleSheet,
TextInput,
Linking,
Alert,
Navigator
} from 'react-native';
import { Button } from 'react-native-elements';
import t from 'tcomb-form-native';
const Form = t.form.Form;
// here we are: define your domain model
const Email = t.subtype(t.Str, (email) => {
const reg = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
});
const LoginFields = t.struct({
username: Email, // a required string
password: t.String, // a required string
});
const options = {
fields: {
password: {
type: 'password',
placeholder: 'Password',
error: 'Password cannot be empty'
},
username: {
placeholder: 'e.g: abc#gmail.com',
error: 'Insert a valid email'
}
}
}; // optional rendering options (see documentation)
export class ChildComponent extends Component {
render() {
if(this.props.result) {
var res = this.props.result.map((item, i) => {
return(
<Text key={i}>{item.useremail}</Text>
)
})
}
return (
<View>
{res}
</View>
)
}
}
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
buttonState: true,
value: {}
}
}
_onSubmit() {
const value = this.refs.form.getValue();
if (value) { // if validation fails, value will be null
console.log(value);
// value here is an instance of LoginFields
}
componentDidMount() {
fetch('http://192.168.100.160:6016/admin/login', {
method: 'POST',
headers: {
'Accept': 'application/x-www-form-urlencoded',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({
useremail: 'kirti#pws.com',
userpassword: '1234',
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState ({
data: responseJson.admin/login
})
})
}
this.props.navigator.push({
id: 'Home'
});
}
onChange = () => {
const value = this.refs.form.getValue();
if(value) {
this.setState({
value,
buttonState: false
});
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
</View>
<View style={styles.content}>
<Text style={styles.contentHeader}>
Pateast Login
</Text>
<View style={styles.loginFormContent}>
<Form
ref="form"
type={LoginFields}
options={options}
value={this.state.value}
onChange={this.onChange}
/>
<Text style={{color: 'blue', marginBottom: 10}}
onPress={() => Linking.openURL('https://www.google.co.in')}>
Forgot Password?
</Text>
<Button
raise
icon={{name: 'key', type: 'octicon'}}
onPress={this._onSubmit.bind(this)}
title="Login"
disabled={this.state.buttonState}
accessibilityLabel="Ok, Great!"
/>
</View>
</View>
<View style={styles.footer}>
</View>
<ChildComponent status={this.state.status} result={this.state.data} />
</View>
);
}
}
const styles = StyleSheet.create(
{
container: {
flex: 1
},
contentHeader: {
// fontFamily: 'sans-serif-condensed',
fontWeight: 'bold',
fontSize: 40,
alignSelf: 'center',
marginBottom: 30
},
header : {
flex: 0.5,
backgroundColor: '#008080'
},
content: {
flex: 10,
backgroundColor: '#f8f8ff',
justifyContent: 'center'
},
loginFormContent: {
marginHorizontal: 20
},
footer: {
flex: 0.5,
backgroundColor: '#008080'
},
loginText: {
fontSize: 20,
marginBottom: 10
},
inputFields: {
fontSize: 20,
borderStyle: 'solid',
borderColor: '#000000',
borderRadius: 30,
marginBottom: 10
}
}
);

you were just one step away from your goal. The only thing you have to change is your body object in your post request. This object has to be a FormData https://developer.mozilla.org/de/docs/Web/API/FormData
Try to set the body like this:
let data = new FormData();
data.append("useremail", 'kirti#pws.com');
data.append("userpassword", '1234');
After that your fetch request should look like this:
fetch('http://192.168.100.160:6016/admin/login', {
method: 'POST',
headers: {
'Accept': 'application/x-www-form-urlencoded',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data
}
...

Related

Want to transfer login status from store to Login Screen for wrong credentials identification

I have to React Native IOS App with Login Screen for users. In the store auth, I am getting string output from Login API as 'success' or 'Login Failed'.I want to transfer this login status to Login Screen, to tell the user about the wrong credentials. Below is the auth store:
auth.js:
export const LOGIN ='LOGIN';
export const login=(textemailid,textpassword) =>{
const formData = new FormData();
formData.append('txtUemail',textemailid);
formData.append('txtUpass',textpassword);
return async dispatch =>{
await fetch('https:/-------------------/login.php',
{
method:'post',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: formData
})
.then(res => res.text())
.then(
(loginresult) =>{
var login = loginresult.replace('\r\n\r\n\r\n\t\r\n\t\r\n\t','');
console.log('loginstatus is '+login);
}).catch(err =>{
console.log(err);
})
dispatch({type:LOGIN,loginStatus:login});
}
}
I want to transfer the 'login' value to Login Screen using navigation. Below is the LoginScreen code:
LoginScreen.js:
import React,{useEffect} from 'react';
import { ActivityIndicator,StyleSheet, Text, View
,KeyboardAvoidingView,TouchableOpacity,Image} from "react-native";
import { Button } from 'react-native-elements';
import { ScrollView } from "react-native-gesture-handler";
import { HelperText,TextInput } from 'react-native-paper';
import { useDispatch } from 'react-redux';
import * as authActions from '../../store/actions/auth';
import Icon from 'react-native-vector-icons/FontAwesome5';
import AsyncStorage from '#react-native-async-storage/async-
storage'
import Toast from 'react-native-root-toast';
const LoginScreen = ({route}) => {
const [textemailid, setTextEmailId] = React.useState('');
const [textpassword, setTextPassword] = React.useState('');
const [isLoading,setIsLoading] = React.useState(false);
const [error, setError] = React.useState('');
const dispatch = useDispatch();
const loginStatus1 = useSelector(state =>
state?.auth?.login_Status); **getting login_Status from auth reducer**
//console.log(state);
console.log('login status is '+loginStatus1)
const loginHandler = async () => {
let action
action = authActions.login(
textemailid,
textpassword
);
setError(null);
setIsLoading(true);
try{
dispatch(action);
console.log('login status is '+loginStatus);
if(loginStatus === 'Login Failed'){
let toast_success = Toast.show('Wrong Credentials');
setIsLoading(false);
}
else if(loginStatus === 'success'){
props.navigation.navigate({routeName:'Home'});
}
} catch(err){
setError(err.message);
console.log(err.message);
setIsLoading(false);
}
};
return(
<KeyboardAvoidingView style={styles.container}>
<ScrollView>
<View style={styles.container}>
<View style={styles.subView}>
<Image
style={{flex:1, height: 100, width: 100,alignSelf:'center',bottom:350}}
source={require('../../assets/profile1.png')}
resizeMode="contain"
/>
<View style={styles.welcometextview}>
<Text style={styles.welcometext}>Welcome!</Text>
{/* <Loader loading={isLoading} color="#ff66be" title='Loading'/> */}
</View>
<View style={styles.textinputemailview}>
<TextInput
underlineColor='grey'
style={styles.textinputemail}
label='Email'
keyboardType="email-address"
editable={true}
autoCapitalize = 'none'
value={textemailid}
theme={{ colors: { placeholder: "#f5f5f5", background: "transparent", text:
'green', primary: '#D43790' } }}
onChangeText={textemailid=>setTextEmailId(textemailid)}>
</TextInput>
</View>
<View style={styles.textinputpasswordview} >
<TextInput style={styles.textinputpassword}
underlineColor='grey'
label='Password'
autoCapitalize = 'none'
editable={true}
value={textpassword}
onChangeText={textpassword => setTextPassword(textpassword)}
theme={{ colors: { placeholder: "#f5f5f5", background: "transparent",text:
'green',primary: '#D43790' } }}>
</TextInput>
</View>
<View style={styles.loginbuttonview}>
{isLoading ? (
<ActivityIndicator size='small' color='green'/>
) :
(
<Button buttonStyle={{
backgroundColor: "#EB4207"
}}
containerStyle={{
marginTop: 12,
width: "50%"
}}
onPress={
() => { loginHandler();
}}
title='Log in'/>
)}
</View>
</View>
<TouchableOpacity style={styles.textforgotpasswordview} onPress=.
{()=>props.navigation.navigate('ForgotPasswordPage')}>
<Text style={styles.textforgotpassword}>Forgot your password?</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.textregisterview} onPress=.
{()=>props.navigation.navigate('SignUp')} >
<Text style={styles.textregister}>Not a member?Sign up now</Text>
</TouchableOpacity>
</View>
</ScrollView>
</KeyboardAvoidingView>
)}
const styles = StyleSheet.create({
container: {
backgroundColor: '#0B0B45',
flex:1,
},
subView: {
backgroundColor: '#1D1F33',
height: 750,
marginTop: 150,
borderTopRightRadius: 40,
borderTopLeftRadius: 40,
},
welcometextview:{
bottom:'80%',
justifyContent:'center',
alignItems:'center'
},
welcometext:{
fontWeight:'bold',
color:'grey',
fontSize:20,
},
textinputemailview:{
position:'absolute',
top:'23%',
width:'80%',
alignSelf:'center'
},
textinputemail:{
backgroundColor:'transparent',
fontWeight:'bold',
fontSize:20,
},
textinputpasswordview:{
position:'absolute',
top:'35%',
width:'80%',
alignSelf:"center"
},
textinputpassword:{
backgroundColor:'transparent',
fontWeight:'bold',
fontSize:20,
},
textregisterview:{
position:'absolute',
top:'75%',
alignSelf:'center'
},
textregister:{
color: "#EB4207",
fontSize: 20,
fontWeight: "bold",
textDecorationLine: 'underline'
},
textforgotpasswordview:{
position:'absolute',
alignSelf:'center',
bottom:'33%'
},
textforgotpassword:{
color: "white",
fontSize: 20,
fontWeight: "bold",
},
loginbuttonview:{
bottom:'45%',
justifyContent:'center',
alignItems:'center'
},
});
export default LoginScreen;
Below is the auth reducer:
auth.js:
import { GETDEVICEINFO, LOGIN,LOGOUT } from '../actions/auth';
const initialState = {
mobileno: null,
login_Status:null,
availableDevice:[],
};
export default (state = initialState,action) => {
switch(action.type){
case LOGIN:
return {
login_Status : action.loginStatus
};
case GETDEVICEINFO:
return {
availableDevice:action.devices
}
case LOGOUT:
return initialState;
default: return state;
}
}
I don't think async storage will work here because I don't want to persist data but only want to get data from auth store and also using AsyncStorage will not flush old data, it stores data till u logout and login.
After running the above code, I am getting the whole function as below:
login status is function login(textemailid, textpassword) {
var formData = new FormData();
formData.append('txtUemail', textemailid);
formData.append('txtUpass', textpassword);
return function _callee(dispatch) {
return _regenerator.default.async(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return _regenerator.default.awrap(fetch('https:--------
-/login.php', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: formData
}).then(function (res) {
return res.text();
}).then(function (loginresult) {
var login =
loginresult.replace('\r\n\r\n\r\n\t\r\n\t\r\n\t', '');
console.log('login1 is ' + login);
saveDataToStoragelogin(login, textemailid);
}).catch(function (err) {
console.log(err);
}));
case 2:
dispatch({
type: LOGIN,
loginStatus: login
});
case 3:
case "end":
return _context.stop();
}
}
}, null, null, null, Promise);
};
Can anyone say how to get only login_Status string. Thanks in Advance?
I would try to change
try{
props.navigation.navigate('LoginScreen', {
paramKey: login,
})
to
try{
navigation.navigate('LoginScreen', {
paramKey: login,
})
No need to pass navigation prop to auth store. When you dispatch({type:LOGIN}) with payload store that state in reducer.Get the State using UseSelector.
For example you are in Screen A and did login Api call and store api response data in reducer. In same screen use useSelector to get the api data response from reducer. based on response type navigate to respected screens. Don't place api call in reducers.
Please check this example https://github.com/raduungurean/react-native-redux-auth-login-logout-example

How to get value from login and show at home

I want to show username and role at home.js
Im following a tutor but got error undefined is not an object (evaluating '_this.props.navigation.navigate') ..
Maybe someone can help me..
This is Form.js
import React, { Component } from 'react';
import { Text, View, StyleSheet, TextInput, TouchableOpacity, AsyncStorage} from 'react-native';
import { Actions } from 'react-native-router-flux';
const ACCESS_TOKEN = 'access_token';
export default class Form extends Component {
constructor(props){
super(props);
this.state ={
grant_type : "password",
scope : "",
client_id : "",
client_secret : "",
username : "",
password : "",
error : "",
accessTokennya : "",
};
}
async storeToken(accessToken){
try{
await AsyncStorage.setItem(ACCESS_TOKEN, accessToken);
this.getToken();
}catch (error){
console.log("something where wrong")
}
}
async getToken(){
try{
let token = await AsyncStorage.getItem(ACCESS_TOKEN);
console.log("token is : "+ token)
}catch (error){
console.log("something where wrong")
}
}
async removeToken(){
try {
let token = await AsyncStorage.removeItem(ACCESS_TOKEN);
this.getToken();
} catch(error){
console.log("Something went wrong")
}
}
async onLoginPressed(){
try {
let response = await fetch('https://bpm.asihputera.or.id/asihputera/oauth2/token', {
method: 'POST',
headers: {
'Content-Type' : 'application/json',
'Accept-Encoding' : 'gzip, deflate',
'Authorization' : 'Bearer cde4e4bc600afcb604fb2ba078c60a16e29dac04',
'User-Agent' : 'PostmanRuntime/7.15.2',
'Accept' : '*/*',
'Cache-Control' : 'no-cache',
'Postman-Token' : 'ad9e715b-a2af-4f3f-86dd-11a7b6ec6037,f00ce420-e144-47ec-be83-756ec1fbc5d2',
'Host' : 'bpm.asihputera.or.id',
'Cookie' : 'PM-TabPrimary=101010010; singleSignOn=0',
'Content-Length' : '139',
'Connection' : 'keep-alive',
'cache-control' : 'no-cache',
},
body: JSON.stringify({
'grant_type' : "password",
'scope' : '*',
'client_id' : 'QKQYKIBJUXFRMGITBPKXVBWOVMFYPWWF',
'client_secret' : '2922119675d440616c9a613026663027',
'username' : this.state.username,
'password' : this.state.password,
}),
});
let res = await response.text();
if (response.status >= 200 && response.status <=300) {
this.setState({error:""});
let accessToken = res;
this.storeToken(accessToken);
console.log("res token: "+accessToken);
username = this.state.username;
Actions.Cases();
} else {
let error = res;
throw error;
}
} catch(error){
this.removeToken();
this.setState({error: error});
console.log("error" + error);
}
}
render(){
const {navigate} = this.props.navigation
return(
<View style={styles.container}>
<TextInput style={styles.inputBox}
editable={true}
onChangeText = {(username)=> this.setState({username})}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Username"
ref='username'
returnKeyType='next'
value={this.state.username}
placeholderTextColor="#ffffff"
selectionColor="#fff"/>
<TextInput style={styles.inputBox}
editable={true}
onChangeText={(password) => this.setState({password})}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder='Password'
ref='password'
returnKeyType='next'
secureTextEntry={true}
value={this.state.password}
placeholderTextColor="#ffffff"
selectionColor="#fff"/>
<TouchableOpacity style={styles.button} onPress={this.onLoginPressed.bind(this)}>
<Text style={styles.buttonText}> Log In </Text>
</TouchableOpacity>
<Text>
{this.state.error}
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container :{
flexGrow:1,
justifyContent:'center',
alignItems:'center',
},
inputBox: {
width: 300,
backgroundColor:'#C0C0C0',
borderRadius: 25,
paddingHorizontal: 16,
fontSize :14,
color: '#ffffff',
marginVertical: 13
},
buttonText: {
fontSize : 16,
fontWeight : '500',
color: '#ffffff',
textAlign:'center'
},
button: {
width:100,
backgroundColor: '#C0C0C0',
borderRadius: 40,
marginVertical: 30,
paddingVertical: 13
}
});
This is Cases.js
import React, { Component } from 'react';
import { Text, View, StyleSheet, TextInput, TouchableOpacity, AsyncStorage} from 'react-native';
import { Actions } from 'react-native-router-flux';
const ACCESS_TOKEN = 'access_token';
export default class Form extends Component {
constructor(props){
super(props);
this.state ={
grant_type : "password",
scope : "",
client_id : "",
client_secret : "",
username : "",
password : "",
error : "",
accessTokennya : "",
};
}
async storeToken(accessToken){
try{
await AsyncStorage.setItem(ACCESS_TOKEN, accessToken);
this.getToken();
}catch (error){
console.log("something where wrong")
}
}
async getToken(){
try{
let token = await AsyncStorage.getItem(ACCESS_TOKEN);
console.log("token is : "+ token)
}catch (error){
console.log("something where wrong")
}
}
async removeToken(){
try {
let token = await AsyncStorage.removeItem(ACCESS_TOKEN);
this.getToken();
} catch(error){
console.log("Something went wrong")
}
}
async onLoginPressed(){
try {
let response = await fetch('https://bpm.asihputera.or.id/asihputera/oauth2/token', {
method: 'POST',
headers: {
'Content-Type' : 'application/json',
'Accept-Encoding' : 'gzip, deflate',
'Authorization' : 'Bearer cde4e4bc600afcb604fb2ba078c60a16e29dac04',
'User-Agent' : 'PostmanRuntime/7.15.2',
'Accept' : '*/*',
'Cache-Control' : 'no-cache',
'Postman-Token' : 'ad9e715b-a2af-4f3f-86dd-11a7b6ec6037,f00ce420-e144-47ec-be83-756ec1fbc5d2',
'Host' : 'bpm.asihputera.or.id',
'Cookie' : 'PM-TabPrimary=101010010; singleSignOn=0',
'Content-Length' : '139',
'Connection' : 'keep-alive',
'cache-control' : 'no-cache',
},
body: JSON.stringify({
'grant_type' : "password",
'scope' : '*',
'client_id' : 'QKQYKIBJUXFRMGITBPKXVBWOVMFYPWWF',
'client_secret' : '2922119675d440616c9a613026663027',
'username' : this.state.username,
'password' : this.state.password,
}),
});
let res = await response.text();
if (response.status >= 200 && response.status <=300) {
this.setState({error:""});
let accessToken = res;
this.storeToken(accessToken);
console.log("res token: "+accessToken);
username = this.state.username;
Actions.Cases();
} else {
let error = res;
throw error;
}
} catch(error){
this.removeToken();
this.setState({error: error});
console.log("error" + error);
}
}
render(){
const {navigate} = this.props.navigation
return(
<View style={styles.container}>
<TextInput style={styles.inputBox}
editable={true}
onChangeText = {(username)=> this.setState({username})}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Username"
ref='username'
returnKeyType='next'
value={this.state.username}
placeholderTextColor="#ffffff"
selectionColor="#fff"/>
<TextInput style={styles.inputBox}
editable={true}
onChangeText={(password) => this.setState({password})}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder='Password'
ref='password'
returnKeyType='next'
secureTextEntry={true}
value={this.state.password}
placeholderTextColor="#ffffff"
selectionColor="#fff"/>
<TouchableOpacity style={styles.button} onPress={this.onLoginPressed.bind(this)}>
<Text style={styles.buttonText}> Log In </Text>
</TouchableOpacity>
<Text>
{this.state.error}
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container :{
flexGrow:1,
justifyContent:'center',
alignItems:'center',
},
inputBox: {
width: 300,
backgroundColor:'#C0C0C0',
borderRadius: 25,
paddingHorizontal: 16,
fontSize :14,
color: '#ffffff',
marginVertical: 13
},
buttonText: {
fontSize : 16,
fontWeight : '500',
color: '#ffffff',
textAlign:'center'
},
button: {
width:100,
backgroundColor: '#C0C0C0',
borderRadius: 40,
marginVertical: 30,
paddingVertical: 13
}
});
And then, this is a Login.js
import React, { Component } from 'react';
import { Text, View, StyleSheet, StatusBar, TouchableOpacity } from 'react-native';
import Logo from '../components/Logo';
import Form from '../components/Form';
import {Actions} from 'react-native-router-flux';
export default class Login extends Component {
render() {
return(
<View style={styles.container}>
<Logo/>
<Form type ="Login"/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
backgroundColor : '#FFFFE0',
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
signupTextCont: {
flexGrow: 1,
alignItems: 'center',
justifyContent: 'flex-end',
paddingVertical: 16,
flexDirection: 'row'
},
signupText:{
color: 'rgba(255,255,255, 0.7)',
fontSize: 16,
paddingVertical: 30,
marginVertical: 30
},
signupButton: {
color: '#ffffff',
fontSize: 16,
fontWeight:'500'
}
});
I hope i get a solution at here :D thank you
Try using this in : Login.js
render() {
return(
<View style={styles.container}>
<Logo navigation = {this.props.navigation}/>
<Form navigation = {this.props.navigation}
type ="Login"/>
)
In your Form.js, with Actions.Cases(); you can pass the values you want to pass as
Actions.Cases({"userName" :this.state.username ,"Password: : this.state.password})
In Cases.js file when you want to get the username just write
this.props.userName
whatever you want to get from one page to other page just need to add
this.props.(key which you've passed in last page)

Invariant Violantion expected string, getting object--from php page that echos a string

I'm extremely new to React Native. I'm logging in a user. Here's the tutorial I'm going off. I had to use XMLHttpRequest instead of fetch because I couldn't get it to pass the POST parameters correctly. The PHP page it posts to just echos out the userID before returning. It's not returning a json string or anything.
I'm logging in the user and using
this.setState({ userID: request.responseText });
to keep track of the userID. This line is giving me the Invariant Violation error, that it expects a string and I'm giving it an object.
App.js ( I included the commented out fetch in case you saw any obvious answers)
import React, { Component } from 'react'
import { View, Text, Alert, Button, TextInput, TouchableOpacity } from 'react-native';
import Home from './Home';
export default class App extends Component{
state = {
email: '',
pwd: '',
auth_token: '',
userID: ''
}
Login = async () => {
var request = new XMLHttpRequest();
var params = "email=" + this.state.email + "&pwd=" + this.state.pwd;
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
Alert.alert(request.responseText); //this is returning the correct value
if(request.responseText != "ERROR"){
this.setState({ userID: request.responseText });
Alert.alert("Welcome", " You have succesfully logged in");//also returning
}else{
Alert.alert("Oh, no!", " There was a problem");
}
} else {
console.warn('error');
}
};
request.open('POST', 'https://mysitexzy.com/wLoginCE');
request.send(params);
/*
fetch('https://mysitexzy.com/wLoginCE', {
method: 'post',
headers: {
Accept: 'application/json',
// 'Content-Type': 'application/json',
},
body: JSON.stringify({
// "provider": "username",
"email": this.state.email,
"pwd": this.state.pwd
})
}).then((response) => response.json())
.then((res) => {
if(typeof(res.message) != "undefined"){
Alert.alert("Error", "Error: "+ res.message);
}
else{
this.setState({ userID: response });
Alert.alert("Welcome", " You have succesfully logged in");
}
}).catch((error) => {
console.error(error);
});
*/
}
render(){
//If auth token is not present
if(this.state.userID==''){
return(
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'stretch',
}}>
<TextInput
placeholder="Enter User name"
onChangeText={ TextInputValue =>
this.setState({email : TextInputValue }) }
underlineColorAndroid='transparent'
style={
{
textAlign: 'center',
width: '90%',
marginBottom: 7,
height: 40,
borderRadius: 5 ,
fontSize: 20,
}
}
/>
<TextInput
placeholder="Enter password"
onChangeText={ TextInputValue =>
this.setState({pwd: TextInputValue }) }
underlineColorAndroid='transparent'
secureTextEntry={true}
style={
{
textAlign: 'center',
width: '90%',
marginBottom: 7,
height: 40,
borderRadius: 5 ,
fontSize: 20,
}
}
/>
<TouchableOpacity onPress={this.Login.bind(this)}>
<View style={{height: 50, backgroundColor:
'#cc0066',justifyContent: 'center',
alignItems: 'center',}}>
<Text style={{
fontSize: 20,
color: '#FFFFFF',
}}>
Login </Text>
</View>
</TouchableOpacity>
</View>
);
}
/* Checking if the auth token is not empty directly sending the user to Home screen */
else{
return(
<Home />
);
}
}
}
Home.js is blank per the instructions in the tutorial.

Update a value in React Native Realm Database

I have a realm database in my React Native Project. I want to update the value of the language in another page. I was able to write the value initially but am I Am stuck updating it. Below is my code.
Profile Schema (Realm Database Schema)
'use strict';
import Realm from 'realm';
class Profile extends Realm.Object {}
Profile.schema = {
name: 'Profile',
properties: {
Onetime: 'string',
Name: 'string',
Email: 'string',
Phone: 'string',
Language:'string',
Url:'string',
},
};
export default new Realm({schema: [Profile]});
Loading Initial Data
let objects = realm.objects('Profile');
var name,url,phone,onetime;
if (firebase.auth().currentUser.displayName == null ) {
onetime= 'true';
name= 'Name';
url = 'https://media2.giphy.com/media/sbLpwwHlgls8E/giphy.gif';
phone = '0000000000';
}
else {
onetime= 'true';
name=firebase.auth().currentUser.displayName;
url=firebase.auth().currentUser.photoURL;
phone = '0000000000';
}
if (objects.length == 0) {
realm.write(() => {
realm.create('Profile', { Onetime: onetime, Name: name, Email: firebase.auth().currentUser.email, Phone:phone, Language: 'e', Url: url, });
});
}
else {
realm.write(() => {
realm.delete(objects);
realm.create('Profile', { Onetime: onetime, Name: name, Email: firebase.auth().currentUser.email, Phone:phone, Language: 'e', Url: url, });
});
}
Activity where I have to update the value
import React from 'react';
import {
ScrollView,
View,
StyleSheet
} from 'react-native';
import {
RkText,
RkTextInput,
RkAvoidKeyboard,
RkTheme,
RkStyleSheet
} from 'react-native-ui-kitten';
import {SocialSetting} from '../../components';
import {FontAwesome} from '../../assets/icons';
import {GradientButton} from '../../components';
import Avatar from 'react-native-interactive-avatar';
import ImagePicker from 'react-native-image-crop-picker';
import realm from '../../realm';
import firebase from 'firebase';
import {RkSwitch} from '../../components/switch/index';
import RadioForm, {RadioButton, RadioButtonInput, RadioButtonLabel} from 'react-native-simple-radio-button';
var radio_props = [
{label: 'English ', value: 'e' },
{label: 'Malayalam', value: 'm'}
];
var lange = '';
var objects = realm.objects('Profile');
export class ProfileSettings extends React.Component {
static navigationOptions = {
title: 'Profile Settings'.toUpperCase()
};
constructor(props) {
super(props);
this.state = {
name: objects[0].Name,
email: objects[0].Email,
phone: objects[0].Phone,
language:objects[0].Language,
url:objects[0].Url,
lang:''
}
}
pickimage(){
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: true
}).then(image => {
console.log("imagelink- "+image);
});
}
handleLogOut() {
firebase.auth().signOut();
}
handleSave() {
alert("Language is: "+lange);
}
updateuser(){
var user = firebase.auth().currentUser;
user.updateProfile({
displayName: this.state.name,
email: this.state.email
}).then(function() {
alert("Update SuccessFull");
}).catch(function(error) {
// An error happened.
alert("Update Failed");
});
}
render() {
if (this.state.language == 'e') {
var val = 0;
}
else {
var val = 1;
}
return (
<ScrollView style={styles.root}>
<RkAvoidKeyboard>
<View style={styles.header}>
<Avatar
uri={this.state.url}
size={'default'}
/>
</View>
<View style={styles.section}>
<View style={[styles.row, styles.heading]}>
<RkText rkType='header6 primary'>INFO</RkText>
</View>
<View style={styles.row}>
<RkTextInput label='Name'
value={this.state.name}
rkType='right clear'
onChangeText={(text) => this.setState({name: text})}/>
</View>
<View style={styles.row}>
<RkTextInput label='Email'
value={this.state.email}
onChangeText={(text) => this.setState({email: text})}
rkType='right clear'/>
</View>
</View>
<View style={styles.section}>
<View style={[styles.row, styles.heading]}>
<RkText rkType='primary header6'>CHOOSE YOUR LANGUAGE</RkText>
</View>
<View>
<View style={styles.radio}>
<RadioForm
radio_props={radio_props}
initial={val}
onPress={(value) => {
{
this.setState({lang:value})
this.setState({language: this.state.lang})
lange = value;
}}}
/>
</View>
</View>
</View>
<GradientButton rkType='large' style={styles.button} text='SAVE' onPress={this.handleSave} />
<GradientButton rkType='large' style={styles.button} text='LOGOUT' onPress={this.handleLogOut}/>
</RkAvoidKeyboard>
</ScrollView>
)
}
}
let styles = RkStyleSheet.create(theme => ({
root: {
backgroundColor: theme.colors.screen.base
},
header: {
backgroundColor: theme.colors.screen.neutral,
paddingVertical: 25,
justifyContent: 'center',
alignItems: 'center'
},
section: {
marginVertical: 25
},
radio: {
flexDirection:'row',
margin:20
},
heading: {
paddingBottom: 12.5
},
row: {
flexDirection: 'row',
paddingHorizontal: 17.5,
marginTop:15,
borderBottomWidth: StyleSheet.hairlineWidth,
borderColor: theme.colors.border.base,
alignItems: 'center',
justifyContent: 'space-between',
flex:1
},
button: {
marginHorizontal: 16,
marginBottom: 32
}
}));
I want to update the value of language in the handleSave()
Any help would be highly appreciated.
Thanks in Advance.
Solved the problem. Here is the solution
handleSave() {
//alert("Language is: "+lange);
let updt = realm.objects('Profile');
realm.write(() => {
updt[0].Language = lange;
});
alert("Language is: "+updt[0].Language);
}
Just create an object of the schema and update the value of the particular field.

React Native post a literal string works but failed on post a state variable

It failed when I tried to post a variable as:
body: JSON.stringify({
username: this.state.username, // it doesn't work,
}),
but everything is good if post as:
body: JSON.stringify({
username: 'literal string', // it works well
}),
I can get the correct value of this.state.username from console.log, so what is the problem on the post? Here is the completed code:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
} from 'react-native';
const REQUEST_URL = 'http://localhost:8000/user';
export default class AddAUser extends Component {
constructor(props) {
super(props);
this.state = {
username: null,
submit: false,
}
}
async _signup() {
try {
await this.setState({
username: this.state.username,
submit: true
});
let response = await fetch(REQUEST_URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.username, // it doesn't work,
// username: console.log(this.state.username), // get correct value from TextInput
// username: 'literal string', // it works well
}),
});
await console.log(response);
} catch (error) {
console.log(error);
}
}
render() {
return (
<View style={styles.container}>
<TextInput style={styles.textInputBox} placeholder='Username' value={this.state.username} onChangeText={(username) => this.setState({username: username})} />
<TouchableOpacity
style={styles.submitButton}
onPress={() => this._signup()}
>
<Text>Sign Up</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
textInputBox: {
height: 40,
borderColor: 'lightblue',
borderWidth: 1,
borderRadius: 5,
margin: 20,
paddingLeft: 10,
},
submitButton: {
marginTop: 20,
paddingTop: 5,
paddingBottom: 5,
paddingLeft: 20,
paddingRight: 20,
backgroundColor: 'lightblue',
borderRadius: 5,
}
});
I'm not sure what you're trying to achieve with using async + await, it's not explained in the context.
I tried without them at: https://rnplay.org/apps/8U6_sA, and it seems to work like expected.