I'm wondering what is the proper way to this: Currently I have an "item/s" that comes from my database for display, from here I'm trying to send an "item/s" back to my database once a user taps the send button.
With this code, I'm having the following output:
Nodemon example:
console.log example:
Here's my code
export default class Dishes extends Component {
constructor(props) {
super (props)
this.state = {
data: [],
id: [],
price: [],
count: '',
SplOrder: '',
name: '',
menu_price: '',
tbl: this.props.navigation.state.params.tbl,
orderDet: this.props.navigation.state.params.orderDet,
}
}
submit = ({ item, index }) => {
fetch('http://192.168.254.102:3308/SendOrder/Send', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
order_no: this.state.orderDet,
tbl_id: this.state.tbl,
//special_request: this.state.SplOrder,
menu_desc: this.state.name, //item
menu_price: this.state.menu_price, //item
//order_quantity: this.state.count,
})
}).then(res => res.json())
.then((responseJson) => {
Alert.alert(JSON.stringify(responseJson))
console.log(responseJson);
})
.catch(error => console.error('Error:', error))
}
componentDidMount() {
this.fetchData();
}
_renderItem = ({ item, index }) => {
return (
<View>
<Text>Name: { name }</Text>
<Text>Price: ₱{ price }</Text>
<Text>Status: { item.menu_status }</Text>
</View>
)
}
render() {
return (
<View>
<FlatList
data = {this.state.data}
keyExtractor = {(item, index) => index.toString()}
extraData = {this.state}
renderItem = {this._renderItem} />
<View>
<TouchableOpacity
onPress = {(item) => this.submit(item)}>
<Text style = {styles.SendText}>Send Order</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
UI sample:
Related
I am sending params through navigation in back direction. from screen B to A. but when I console this.props.route.params.value then I am getting undefined error. please help. how can I get data which I have send in back direction. I dont know redux. is there any quick way without redux.
here is screen A
import { TouchableOpacity, View } from "react-native";
export default class patientReadings extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
console.log(this.props.route.params.value)
return (
<View>
<TouchableOpacity
onPress={() => this.props.navigation.navigate("B",{value1:"1"})}
>
button 1
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.props.navigation.navigate("B",{value2:"2"})}
>
button 2
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.props.navigation.navigate("B",{value3:"3"})}
>
button 3
</TouchableOpacity>
</View>
);
}
}
here is screen B
export default class medicalInput extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
this.state = {};
}
validateInputs = (event) => {
fetch("api", {
method: "POST",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify([
{
data,
},
]),
})
.then((returnValue) => returnValue.json())
.then((response) => {
console.log(response);
this.props.navigation.navigate("A", {value : this.props.route.params.value1+"1"});
});
};
render() {
return (
<TouchableOpacity
onPress={() => this.validateInputs()}
></TouchableOpacity>
);
}
}
I have been reading a lot of answers on SO as well as GitHub issues trying to implement a solution, but have been unable to come up with a solution for this situation.
Here is a representation of my code:
class MeetingsScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
upcomingMeeting: [],
refreshing: false
};
}
async handlePress() {
const user = await AsyncStorage.getItem('User');
this.props.navigation.navigate('WriteSummary', { id: user.id, type: 'submit' });
}
printUpcomingMeetings = () => {
return (<View style={styles.meeting}>
<Button
containerStyle={styles.meetingButton}
style={styles.meetingButtonText}
onPress={() => this.handlePress(user.id)}
Press me to write summary!
</Button>
</View>);
}
}
render () {
return (<View style={{flex:1}} key={this.state.refreshing}>
{ this.printUpcomingMeetings() }
</View>);
}
}
class WriteSummaryScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
storageId: '',
normalId: -1,
type: '',
curSummary: ''
}
}
componentDidMount = () => {
const { params } = this.props.navigation.state;
const { id, type } = params ? params : null;
const storageId = 'summary_' + id;
this.setState({storageId:storageId});
this.setState({normalId:id});
this.setState({type:type});
AsyncStorage.getItem(storageId).then((value) => this.setSkipValue(value));
}
async setSkipValue (value) {
if (value !== null) {
this.setState({ 'curSummary': value });
} else {
this.setState({ 'curSummary': '' });
}
}
async saveSummary (text) {
this.setState({'curSummary': text});
await AsyncStorage.setItem(this.state.storageId, text);
}
async handleSubmit() {
const user = await AsyncStorage.getItem('User');
if (this.state.type === 'submit') {
// post insert
const postres = fetch (url + '/create-summary', {
method: 'POST',
body: JSON.stringify({
AppointmentId: this.state.normalId,
SummaryText: this.state.curSummary,
UserId: user.Id
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
.catch((error) => {
console.error(error);
});
} else {
// post update
const postres = fetch (url + '/update-summary', {
method: 'POST',
body: JSON.stringify({
AppointmentId: this.state.normalId,
SummaryText: this.state.curSummary,
UserId: user.Id
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
.catch((error) => {
console.error(error);
});
}
this.props.navigation.navigate('Meetings');
}
render () {
return <View style={{flex:1}}>
<View>
<View style={{height:25, backgroundColor: colors.vikingBlue}}></View>
<View style={{height:30, backgroundColor: colors.white}}></View>
<View style={{flexDirection:'row', backgroundColor: colors.white, alignItems:'center'}}>
<View style={{width:5}}></View>
<TouchableOpacity onPress={() => this.props.navigation.goBack()} activeOpacity={0.5}>
<Image style={{width:30, height:30}} source={require('./assets/icons8-back-50.png')} />
</TouchableOpacity>
<View style={{width:10}}></View>
<View style={{width:mainTitleWidth,textAlign:'center',alignItems:'center'}}>
<Text style={{fontSize:22}}>Settings</Text>
</View>
<TouchableOpacity onPress={() => this.props.navigation.navigate('HelpModal')} activeOpacity={0.5}>
<Image style={{width:30, height:30}} source={require('./assets/help.png')} />
</TouchableOpacity>
</View>
<View style={{height:30, backgroundColor: colors.white}}></View>
</View>
<TextInput
multiline
numberOfLines={6}
style={styles.summaryInput}
onChangeText={text => saveSummary(text)}
value={this.state.curSummary} />
<Button
containerStyle={styles.summaryButton}
style={styles.summaryButtonText}
onPress={this.handleSubmit()}>
Submit
</Button>
</View>
}
}
function HomeStack() {
return (
<Tab.Navigator
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="Meetings" component={MeetingsScreen} />
<Tab.Screen name="Topics" component={TopicsScreen} />
</Tab.Navigator>
);
}
export default class AppContainer extends React.Component {
// Main rendering function. Always begins on the SplashScreen, which checks user login status and directs to Meetings. I left it out and the other Tab navigator screens for less clutter.
render() {
return (
<NavigationContainer>
<Stack.Navigator headerMode='none' initialRouteName='Splash'>
<Stack.Screen name='Splash' component={SplashScreen} />
<Stack.Screen name='Main' component={HomeStack} />
<Stack.Screen name='WriteSummary' component={WriteSummaryScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
};
I get the error TypeError: undefined is not an object (evaluating '_this7.props.navigation.state.params)' after pressing the button on MeetingsScreen and navigating to WriteSummaryScreen.
What confuses me is the screen is navigated to, so the data should have been passed. What am I missing?
You can access parametes like below if its class based component:
class WriteSummaryScreen extends React.Component {
const {id, type} = this.props.route.params;
//........
for the functional component:
const WriteSummaryScreen =({navigation, route})=>{
const {id, type} = route.params;
//..........
}
You can access the params that you have passed from a screen using the getParam function.
so you can use this code:
const id = this.props.navigation.getParam("id");
const type = this.props.navigation.getParam("type");
What ended up working for me was the following:
const id = this.props.route.params.id;
const type = this.props.route.params.type;
I am trying to load a Flat List with some items fetched from firebase. I have been able to validate that I am getting the data from firebase.
After data is fetched I update an state key "isLoading" to false, to show the flatList.
Just to test I have set data as a static set of values, but still it does not render.
Any ideas why?
export default class ListScreen extends Component {
state = {
posts: [],
isLoading: true
}
componentDidMount() {
fetch('https://test.firebaseio.com/posts.json', {
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
return response.json();
})
.then(items => {
this.setState({
posts: items,
isLoading: false
})
}).catch(err => {
alert(JSON.stringify(err));
});
}
render() {
const activityIndicator = <ActivityIndicator />
let list;
if(this.state.isLoading) {
list = activityIndicator
} else {
list = <FlatList style={{flex: 1}} data={[{key: 'a'}, {key: 'b'}]} renderItem={({item}) => {
return <Text>{item.key}</Text>
}} keyExtractor={(item) => { return item.key; }} />
}
return (
<View style={styles.container}>
<Text>Posts</Text>
<Button title="Add Post" onPress={() => {
this.onAddPost();
}} />
<View>{list}</View>
</View>
)
}
onAddPost = () => {
this.props.navigation.navigate('create');
}
}
Just remove style={{flex: 1}} from the FlatList
So I am following this guide and my web host works, but a client still get an error:
JSON Parse error: Unexpected identifier "Try"
This is how my register.js code looks like:
import React, { Component } from "react";
import {
StyleSheet,
Text,
View,
StatusBar,
TouchableOpacity,
Alert,
TextInput
} from "react-native";
import { navigation } from "react-navigation";
import Form from "../forms/Form";
export default class Register extends Component<{}> {
constructor(props) {
super(props);
this.state = {
UserName: "",
UserEmail: "",
UserPassword: ""
};
}
UserRegistrationFunction = () => {
const { UserName } = this.state;
const { UserEmail } = this.state;
const { UserPassword } = this.state;
fetch("https://lifestormweb.000webhostapp.com/user_registration.php", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
name: UserName,
email: UserEmail,
password: UserPassword
})
})
.then(response => response.json())
.then(responseJson => {
Alert.alert(responseJson);
})
.catch(error => {
console.error(error);
});
};
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.inputBox}
underlineColorAndroid="#ffffff"
placeholder="Ihre Name"
placeholderTextColor="#ffffff"
selectionColor="#fff"
onChangeText={UserName => this.setState({ UserName })}
onSubmitEditing={() => this.password.focus()}
/>
<TextInput
style={styles.inputBox}
underlineColorAndroid="#ffffff"
placeholder="Ihre E-mail"
placeholderTextColor="#ffffff"
selectionColor="#fff"
keyboardType="email-address"
onChangeText={UserEmail => this.setState({ UserEmail })}
onSubmitEditing={() => this.password.focus()}
/>
<TextInput
style={styles.inputBox}
underlineColorAndroid="#ffffff"
placeholder="Passwort"
secureTextEntry={true}
placeholderTextColor="#ffffff"
onChangeText={UserPassword => this.setState({ UserPassword })}
ref={input => (this.password = input)}
/>
<TouchableOpacity
onPress={this.UserRegistrationFunction}
style={styles.button}
>
<Text style={styles.buttonText}>Sich anmelden</Text>
</TouchableOpacity>
<View style={styles.signupTextCont}>
<Text style={styles.signupText}>Haben Sie schon einen Account?</Text>
<TouchableOpacity
onPress={() => this.props.navigation.navigate("Login")}
>
<Text style={styles.signupButton}> Sich einloggen</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
module.exports = Register;
The response you are fetching is a string value not JSON.You need convert the response maybe like:
{"result": "Something went wrong.Try again", code: "500"}
Code will verify if the server side response don't have issues.
I tried to make a post request on your mentioned url https://lifestormweb.000webhostapp.com/user_registration.php
and I get this response
which is not a json, so you need to do the handling for such responses in your code, hope it helps!!
I am trying to update my state for nickname and email through textInput and then submit it through a post request to my server. Both keep coming back as undefined. I'm totalling lost as to what I'm doing wrong here.
export default class Add extends Component {
constructor(props){
super(props);
this.state ={
isLoading: true,
nickname: "",
email: ""
}
}
static navigationOptions = {
title: 'Add Contacts',
};
componentDidMount(){
this.setState({
isLoading: false
})
}
onSubmit = () => {
console.log('on submit')
return fetch(`...`, {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain */*',
'Content-Type': 'application/json',
},
body: JSON.stringify(this.state)
})
.then((response) => response)
.then((responseJson) => {
return responseJson
})
.catch((error) => {
throw error;
})
}
render() {
const { navigate } = this.props.navigation;
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View
style={styles.container}
>
<Text
style={{fontSize:30}}>
New Contact
</Text>
<View>
<TextInput
ref= {(el) => { this.nickname = el; }}
onChangeText={(nickname) => this.setState({nickname}, function () {console.log('Nickname updated')})}
value={this.state.nickname}
/>
<TextInput
value={this.state.email}
onChangeText={(text) => this.setState({email: text})}
/>
</View>
<Button
text = {
<Text
style={{color:colors.textColor, textAlign: 'center'}}
>
Save
</Text>
}
onPress= { () => {
this.onSubmit()
navigate('Home')
}
}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: 20,
alignItems: 'center',
justifyContent: 'center',
}
});
.then((response) => response)
Should be:
.then((response) => response.json())
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Making_fetch_requests