I have my react-native app consisting of a form. I have implemented two check-boxes with their state set to boolean true. I want boolean true or false to get submitted to the database from those check-boxes but the check-box button won't work.
Here's my code:
import React, { Component } from 'react';
import { View, Text, Button, TextInput, StyleSheet } from 'react-native';
import { CheckBox } from 'react-native-elements';
import axios from 'axios';
export default class Delivery extends Component {
constructor(props) {
super(props);
this.state = {
trackingNo: '',
weight: '',
length: '',
width: '',
//checked: true,
delivered: { checked: true }
};
}
componentDidMount(){
fetch('https://courierapp-test.herokuapp.com/products/')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
}
onPressSubmit(){
axios.post('https://courierapp-test.herokuapp.com/products/', {
requestId: this.state.trackingNo,
parcelWeight: this.state.weight,
parcelLength: this.state.length,
parcelWidth: this.state.width,
parcelPickup: this.state.pickup,
parcelDelivered: this.state.delivered,
})
.then(function (response) {
console.log(response, "data sent");
})
.catch(function (error) {
console.log(error, "data not sent");
});
}
render() {
return (
<View style={{padding: 15}}>
<TextInput
style={styles.inputStyle}
placeholder="Request Id"
onChangeText={(trackingNo) => this.setState({trackingNo})}
value={this.state.trackingNo}
/>
<CheckBox style={styles.checkStyle}
title='Pickup'
checked={this.state.checked}
/>
<CheckBox style={styles.checkStyle}
title='Delivered'
onValueChange={() => this.setState({ checked: !this.state.checked })}
/>
<TextInput
style={styles.inputStyle}
placeholder="Enter Parcel Weight(Kg)"
onChangeText={(weight) => this.setState({weight})}
value={this.state.weight}
/>
<TextInput
style={styles.inputStyle}
placeholder="Enter Parcel Length(Cm)"
onChangeText={(length) => this.setState({length})}
value={this.state.length}
/>
<TextInput
style={styles.inputStyle}
placeholder="Enter Parcel Width(Cm)"
onChangeText={(width) => this.setState({width})}
value={this.state.width}
/>
<Button
onPress={() => {
this.onPressSubmit()
}
}
title="Submit"
color="#1ABC9C"
/>
</View>
);
}
}
const styles = StyleSheet.create({
inputStyle: {
color: '#1ABC9C',
height: 40,
borderWidth: 0
}
});
I have tried every work around but could not solve it. the checkbox keeps on blinking only upon clicking but could not change the state checked or unchecked and also no value getting submitted to database.
Define variable checked in state
this.state = {
checked: false
};
create a method
onChangeCheck() {
this.setState({ checked: !this.state.checked})
}
And use onChange() prop of Chekbox to update the state and provide value to the check box like this
<CheckBox
style={styles.checkBox}
value={this.state.checked}
onChange={() => this.onChangeCheck()} />
Try changing value inside event onValueChange
<CheckBox value={this.aBooleanField} onValueChange={() => {
this.aBooleanField = !this.aBooleanField;
this.updateView();
}}/>
The updateView is like this:
updateView() {
this.setState({ viewChanged: !this.state.viewChanged})
}
Also works for < Switch /> component, and you can use updateView to only to refresh the view, setState it's to keep state values (when you resume app, rotate screen, etc).
Related
Im building a react-native app, which when the user try to signIn, I invoike firebase.CreateUser and then an api from firebase function to create that user in my database (Firebase Real-Time). The problem is that when the componentDidUpdate is executed, I still don't have the result from my firebaseFunction, then my props only update if I tap in screen. I would like to know how to deal with that.
Im using redux.
Follow my code:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button, Image,Alert} from 'react-native';
import logo from '../../asserts/logo.png'
import { TouchableOpacity, TextInput } from 'react-native-gesture-handler';
import { Divider,Input} from 'react-native-elements';
import axios from 'axios';
import { connect } from 'react-redux';
import { signupUser} from '../../store/actions/Section/actions';
class Signin extends Component {
state = {
fullName:'',
userName:'',
email:'',
password:'',
confirmPassword:'',
bornDate:'',
State:'',
City:''
};
handleEmailChange = val => {
this.setState({ email:val });
};
handlePasswordChange = val => {
this.setState({ password:val });
};
handleConfirmPasswordChange = val => {
this.setState({ confirmPassword:val });
};
handleNameChange = val => {
this.setState({ fullName:val });
};
handleUserNameChange = val => {
this.setState({ userName:val });
};
handleStateChange = val => {
this.setState({ State:val });
};
handleCityChange = val => {
this.setState({ City:val });
};
handleBornDateChange = val => {
this.setState({ bornDate:val });
};
onSignInUser = () => {
const {email,password} = this.state
if(email=='' || password=='')
return;
this.props.signUp(this.state.fullName,this.state.userName, this.state.email,this.state.password,this.state.confirmPassword,this.state.bornDate,this.state.State,this.state.City);
// this.props.navigation.navigate('User');
};
componentDidUpdate() {
const { idUser, loading,error } = this.props;
console.log(idUser);
console.log('aqui');
if (!loading && error) Alert.alert('Erro', error);
if (!loading && idUser) this.props.navigation.navigate('User');
}
render() {
return (
<View style={styles.container}>
<View style={styles.flexCenter}>
<Image source={logo} style={styles.logoImage}/>
<Text style={styles.logoText} >HomeShare</Text>
<Text style={styles.sublogoText} >SignUp</Text>
</View>
<Divider style={styles.divider} />
<View style={styles.flexButton}>
<View style={styles.inputContainer}>
<Input style={styles.textInput} onChangeText={this.handleNameChange} value={this.state.fullName} placeholder='Nome'/>
<Input style={styles.textInput} onChangeText={this.handleUserNameChange} value={this.state.userName} placeholder='User'/>
<Input style={styles.textInput} onChangeText={this.handleBornDateChange} value={this.state.bornDate} placeholder='Nascimento'/>
<Input style={styles.textInput} onChangeText={this.handleStateChange} value={this.state.State} placeholder='Estado'/>
<Input style={styles.textInput } onChangeText={this.handleCityChange} value={this.state.City} placeholder='Cidade'/>
<Input style={styles.textInput} onChangeText={this.handleEmailChange} value={this.state.email} placeholder='E-mail' keyboardType={'email-address'}/>
<Input style={styles.textInput} onChangeText={this.handlePasswordChange} value={this.state.password} placeholder='Senha' secureTextEntry={true}/>
<Input style={styles.textInput} onChangeText={this.handleConfirmPasswordChange} value={this.state.confirmPassword} placeholder='Confirme sua Senha' secureTextEntry={true}/>
</View>
<TouchableOpacity style={styles.button} activeOpacity={0.5} onPress={this.onSignInUser} >
<View>
<Text style={styles.buttonText}>SignIn</Text>
</View>
</TouchableOpacity>
<Text style={{marginTop:10}}>Ou</Text>
<TouchableOpacity style={styles.button} activeOpacity={0.5} onPress={this.signInUser}>
<View>
<Text style={styles.buttonText}>Entrar com Facebook</Text>
</View>
</TouchableOpacity>
</View>
</View>
);
}
}
const mapStateToProps = ({ section: { restoring, loading, user, error, logged, idUser } }) => ({
restoring: restoring,
loading: loading,
user: user,
error: error,
logged: logged,
idUser: idUser
});
const mapDispatchToProps = {
signUp:signupUser
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Signin);
My Action:
export const signupUser = (fullName,userName, email,password,confirmPassword,bornDate,State,City) => dispatch => { dispatch(sessionLoading());
firebaseService.auth().createUserWithEmailAndPassword(email, password).then(user => {
console.log(user);
firebaseService.auth().currentUser.getIdToken(true).then(function(idToken) {
SectionService.signIn(idToken,fullName,userName, email,password,confirmPassword,bornDate,State,City).then((response) =>{
console.log(response);
dispatch(sessionSetId(response));
}).catch(e=> {
dispatch(sessionError(e));
});
}).catch(function(error) {
dispatch(sessionError(e));
});
})
.catch(error => {
dispatch(sessionError(error.message));
});
A proposed solution is to handle the account creation in the createUser callback and to update it with other data in the cloud function. Alternatively you can set up a listener that looks for the document, which will then be created and the listener will be notified.
I personally create the user doc on the client side because I create it with some data only available on the client, but your use case will be dictate your preferred approach.
I have a react native/redux/redux form setup which is (mostly) working, so everything is hooked up and running.
When I set up a form with an asynchronous update, I get a date field, for which I defined a custom component to be used as <Field> in redux-form.
Here's my component:
import React, { Component } from "react";
import { TouchableOpacity, StyleSheet } from "react-native";
import { Text, theme, Button, Block, Input } from "galio-framework";
import DateTimePicker from "react-native-modal-datetime-picker";
export class DateInputField extends Component {
constructor(props) {
super(props);
this.state = { isDateTimePickerVisible: false };
this.handleChange = this.handleChange.bind(this);
}
showDateTimePicker = () => {
this.setState({ isDateTimePickerVisible: true });
};
hideDateTimePicker = () => {
this.setState({ isDateTimePickerVisible: false });
};
handleChange = date => {
console.log("date->" + date);
this.setState({ isDateTimePickerVisible: false, date: date });
this.props.input.onChange(date);
};
render() {
const { input, meta, ...inputProps } = this.props;
return (
<Block style={styles.container}>
<TouchableOpacity onPress={this.showDateTimePicker}>
<DateTimePicker
date={new Date(input.value)}
cancelTextIOS="Annulla"
confirmTextIOS="Conferma"
isVisible={this.state.isDateTimePickerVisible}
onConfirm={this.handleChange}
onCancel={() => this.setState({ isDateTimePickerVisible: false })}
/>
<Input
color={"black"}
editable={false}
// onTouch={this.showDateTimePicker}
// onFocus={this.showDateTimePicker}
label={this.props.label}
style={styles.input}
placeholder={this.props.placeholder}
value={
this.state.date != undefined
? this.state.date.getDate() +
"/" +
(this.state.date.getMonth() + 1) +
"/" +
this.state.date.getFullYear()
: "gg/mm/aaaa"
}
/>
</TouchableOpacity>
</Block>
);
}
}
export const styles = StyleSheet.create({
container: {},
label: {},
input: { flex: 1, color: "red", padding: 0, height: 50 }
});
and my field:
<Field name={"consignment_date"} label="Fine" component={DateInputField} />
This component works, when I press the field the datepicker shows up with the correct date coming from the connected "model" field connected to it.
Now my problem is I can't figure way an elegant way to update the field value when the field is not updated by a human "onChange" event but the component's state is updated (and subsequently the component is rendered). I tried many combinations of setting the state date field, but I always ended in infinite loops because updating the state would cause a render, and so on.
I tried many Component lifecycle events to put my reading of the input.value and setting it on a state.displayedDate property, but I guess I am missing a very obvious way to do this because of my scarce knowledge of React's dynamics.
Any help is really appreciated.
Posting the solution that works:
import React, { Component } from "react";
import { TouchableOpacity, StyleSheet } from "react-native";
import { Text, theme, Button, Block, Input } from "galio-framework";
import DateTimePicker from "react-native-modal-datetime-picker";
export class DateInputField extends Component {
constructor(props) {
super(props);
this.state = { isDateTimePickerVisible: false }; //no more date in state
this.handleChange = this.handleChange.bind(this);
}
showDateTimePicker = () => {
this.setState({ isDateTimePickerVisible: true });
};
hideDateTimePicker = () => {
this.setState({ isDateTimePickerVisible: false });
};
handleChange = date => {
this.setState({ isDateTimePickerVisible: false });
this.props.input.onChange(date);
};
render() {
const { input, meta, ...inputProps } = this.props;
return (
<Block style={styles.container}>
<TouchableOpacity onPress={this.showDateTimePicker}>
<DateTimePicker
style={styles.label}
date={new Date(input.value)}//date is transformed from input
onDateChange={this.handleChange}
cancelTextIOS="Annulla"
confirmTextIOS="Conferma"
isVisible={this.state.isDateTimePickerVisible}
onConfirm={this.handleChange}
onCancel={() => this.setState({ isDateTimePickerVisible: false })}
/>
<Input
color={"gray"}
editable={false}
enabled={false}
label={this.props.label}
style={styles.input}
placeholder={this.props.placeholder}
value={ //value is transformed to a date, then to the local string representation
input.value !== ""
? new Date(input.value).toLocaleDateString()
: new Date().toLocaleDateString()
}
/>
</TouchableOpacity>
</Block>
);
}
}
export const styles = StyleSheet.create({
container: {},
input: {
flex: 1,
color: "red",
height: 50,
borderWidth: 0,
borderBottomWidth: 1
}
});
The goal is to allow the user to input a keyword into a search bar, store the search word or phrase into a string and send a post request to to the movie server and display the results in a FlatList format.
I'm not skilled in javascript, but so far I was able to store the search input into a variable and confirmed it by console logging the search but using that variable to render and display the results in confusing
import React, { Component } from "react";
import {
View,
Text,
FlatList,
StyleSheet
} from "react-native";
import { Container, Header,Item,Input, Left, Body, Right, Button, Icon,
Title } from 'native-base';
class Search extends Component {
constructor(props) {
super(props);
this.state = {text: ''};
this.state = {
dataSource: []
}
}
renderItem = ({item}) => {
return (
<Text>{item.title}</Text>
)}
componentDidMount() {
const apikey = "&apikey=thewdb"
const url = "http://www.omdbapi.com/?s="
fetch(url + this.state.text + url)
.then((response) => response.json())
.then((responseJson)=> {
this.setState({
dataSource: responseJson.Search
})
})
.catch((error) => {
console.log(error)
})
}
render() {
return (
<Container>
<Header
searchBar rounded
>
<Item>
<Icon name="ios-search" />
<Input
placeholder="Type here to translate!"
onChangeText={(text) => this.setState({text})}
/>
</Item>
<Button
transparent
onPress={()=> {
{console.log(this.state.text)}
}
}
>
<Text>Search</Text>
</Button>
</Header>
<FlatList
style={{flex: 1, width:300}}
data={this.state.dataSource}
keyExtractor={(item, index) => 'key'+index}
renderItem={this.renderItem}
/>
</Container>
);
}
}
export default Search;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
});
My code is a bit sloppy so please forgive me on that, I'm still new to coding.
The issue is you are fetching data from API on componentDidMount but it will be called only once (when component gets mounted).
So the best way to fix it is
Create a func called fetchData
fetchData(text) {
this.setState({ text });
const apikey = '&apikey=thewdb';
const url = 'http://www.omdbapi.com/?s=';
fetch(url + text + url)
.then(response => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson.Search,
});
})
.catch((error) => {
console.log(error);
});
}
In onChangeText, call fetchData
<Input
placeholder="Type here to translate!"
onChangeText={(text) => {
this.fetchData(text);
}}
/>
I cannot seem to navigate away from my component despite trying both this.props.navigation.navigate and NavigationService
To test it out, i created a simple button to navigate away and it work but when i used it within my formik and react-native, it did not navigate away
Anyone encountered such situations before? How do you resolve? below is my code
thank you
import React, { Component } from "react";
import {
View,
StyleSheet,
AsyncStorage,
Text,
TouchableHighlight
} from "react-native";
import { Button } from "react-native-elements";
import { Formik } from "formik";
import * as Yup from "yup";
import { Mutation } from "react-apollo";
import Input from "../components/Input";
import NavigationService from "../../navigation/NavigationService";
import { SIGNIN } from "../../graphql/queries";
const FormValidationSchema = Yup.object().shape({
email: Yup.string()
.email("Not valid email")
.required("Email is required"),
password: Yup.string()
.min(3)
.required("Password is required")
});
class EmailSigninScreen extends Component {
_handleSubmit = async (values, bag, signin) => {
console.log(values, bag, signin);
try {
const data = await signin({
variables: {
email: values.email,
password: values.password
}
});
await AsyncStorage.setItem("token", data.signin.token);
this.props.navigation.navigate("Main");
// NavigationService.navigate("Main");
} catch (error) {
bag.setSubmitting(false);
bag.setErrors(error);
}
};
render() {
const { container, buttonStyle } = styles;
return (
<View style={container}>
<Mutation mutation={SIGNIN}>
{(signin, { error }) => {
console.log(error);
return (
<Formik
initialValues={{ email: "", password: "" }}
onSubmit={(values, bag) =>
this._handleSubmit(values, bag, signin)
}
validationSchema={FormValidationSchema}
render={({
values,
handleSubmit,
errors,
touched,
setFieldValue,
setFieldTouched,
isValid,
isSubmitting
}) => (
<React.Fragment>
<Input
label="Email"
autoCapitalize="none"
autoComplete="none"
value={values.email}
onChange={setFieldValue}
onTouch={setFieldTouched}
name="email"
error={touched.email && errors.email}
/>
<Input
label="Password"
autoComplete={false}
autoCapitalize="none"
secureTextEntry
name="password"
value={values.password}
onChange={setFieldValue}
onTouch={setFieldTouched}
error={touched.password && errors.password}
/>
<Button
backgroundColor="purple"
buttonStyle={buttonStyle}
title="Submit"
onPress={handleSubmit}
disabled={!isValid || isSubmitting}
loading={isSubmitting}
/>
<TouchableHighlight
onPress={() => this.props.navigation.navigate("Main")}
>
<Text>Jump</Text>
</TouchableHighlight>
</React.Fragment>
)}
/>
);
}}
</Mutation>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center"
// justifyContent: "center"
},
buttonStyle: {
marginTop: 20,
width: "100%"
}
});
export default EmailSigninScreen;
Try to use withNavigation like this:
import { withNavigation } from 'react-navigation';
export default withNavigation(EmailSigninScreen);
everything else can stay the same
The problem lies in my async - await syntax factoring
factoring my handleSubmit function to below format works...
i am still trying to see if i can convert the codes below to purely using async and await rather than a mixture of async and await & then and catch. if anyone has a solution, will appreciate advise here. Tq
//TODO refactor to async and await syntax
_handleSubmit = (values, bag, signin) => {
signin({
variables: {
email: values.email,
password: values.password
}
})
.then(async ({ data }) => {
if (data && data.signin.token) {
await AsyncStorage.setItem("token", data.signin.token);
this.props.navigation.navigate("Main");
}
})
.catch(err => {
bag.setSubmitting(false);
bag.setErrors(err);
});
};
First I want to start by saying I am a total noob at React Native and Shoutem. I am not sure if I should write Shoutem or React Native in the subject of my questions, but here is my problem.
I have two screens:
Screen1.js
Screen2.js
Screen1 displays a list of items returned from a fetch. Once I click on the item, it will open the second screen which is the details screen.
I am passing data from screen1 to screen2. In screen2 I need to make another fetch call for different data, but it does not work. I am doing exactly the same thing on both screens.
Here is my code for Screen1:
import React, {
Component
} from 'react';
import {
ActivityIndicator,
TouchableOpacity
} from 'react-native';
import {
View,
ListView,
Text,
Image,
Tile,
Title,
Subtitle,
Overlay,
Screen
} from '#shoutem/ui';
import {
NavigationBar
} from '#shoutem/ui/navigation';
import {
navigateTo
} from '#shoutem/core/navigation';
import {
ext
} from '../extension';
import {
connect
} from 'react-redux';
export class List extends Component {
constructor(props) {
super(props);
this.renderRow = this.renderRow.bind(this);
this.state = {
isLoading: true,
content: null,
}
}
componentDidMount() {
return fetch('https://www.cannabisreports.com/api/v1.0/strains').then((response) => response.json()).then((responseData) => {
this.setState({
isLoading: false,
content: responseData
});
}).done();
}
renderRow(rowData) {
const { navigateTo } = this.props;
return (
//<Text>{rowData.name}, {rowData.createdAt.datetime}</Text>
<TouchableOpacity onPress={() => navigateTo({
screen: ext('Strain'),
props: { rowData }
})}>
<Image styleName="large-banner" source={{ uri: rowData.image &&
rowData.image ? rowData.image : undefined }}>
<Tile>
<Title>{rowData.name}</Title>
<Subtitle>none</Subtitle>
</Tile>
</Image>
</TouchableOpacity>
);
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={{flex: 1, paddingTop: 20}}>
<ListView
data={this.state.content.data}
renderRow={rowData => this.renderRow(rowData)}
/>
</View>
);
}
}
// connect screen to redux store
export default connect(
undefined,
{ navigateTo }
)(List);
I am passing rowData to Screen2. I then need to make another fetch calling using data from rowData as it is a path parameter needed for the API call in Screen2.
So basically I need to make a fetch call in Screen2 like this:
fetch('https://mywebsite.com/'+rowData.something+'/myotherdata')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
content: responseJson.data
})
})
.catch((error) => {
console.error(error);
});
Here is my code for screen2:
export default class Strain extends Component {
constructor(props) {
super(props);
this.state = {
content: null,
}
}
componentDidMount() {
return fetch('https://mywebsite.com/'+rowData.something+'/myotherdata')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
content: responseJson.data
})
})
.catch((error) => {
console.error(error);
});
}
renderRow(dataContent) {
return (
<Text>{dataContent.name}</Text>
// This does not work either -> <Text>{dataContent}</Text>
);
}
render() {
const { rowData } = this.props; //This is coming from screen1.js
return (
<ScrollView style = {{marginTop:-70}}>
<Image styleName="large-portrait" source={{ uri: rowData.image &&
rowData.image ? rowData.image : undefined }}>
<Tile>
<Title>{rowData.name}</Title>
<Subtitle>{rowData.createdAt.datetime}</Subtitle>
</Tile>
</Image>
<Row>
<Text>Seed Company: {rowData.seedCompany.name}</Text>
</Row>
<Divider styleName="line" />
<Row>
<Icon name="laptop" />
<View styleName="vertical">
<Subtitle>Visit webpage</Subtitle>
<Text>{rowData.url}</Text>
</View>
<Icon name="right-arrow" />
</Row>
<Divider styleName="line" />
<View style={{flex: 1, paddingTop: 20}}>
<ListView
data={content}
renderRow={dataContent => this.renderRow(dataContent)}
/>
</View>
<Divider styleName="line" />
</ScrollView>
);
}
}
My fetch URL returns data like this:
{
data: {
name: "7.5833",
another_name: "8.6000",
different_name: "5.7500",
}
}
This only returns one data object like what you see above.
When I run the code I get this error:
null is not an object (evaluating 'Object.keys(e[t])')
Please let me know if you need me to provide more info.
I have tried so many different things and nothing seems to work so I am in need of some help. What am I doing wrong?
Not sure why this works but it does.
I used a function to fetch my data and then call the function in componentDidMount like this:
getData() {
return fetch('https://mywebsite.com/myotherdata')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: responseJson.data
});
})
.catch((error) => {
console.error(error);
});
}
componentDidMount() {
this.getData();
}
Then to get the values from the JSON response I am doing this:
this.state.data.name
I am having another issue, but I will create another question.