I have created a form to submit some data in react native. Now I need to connect it existing express backend. Help me to do that. I'm a beginner to react native. The following code is the backend. Now I need to submit product id and the description to the SQL server using express backend. How can I do this. my express backend can't be change. changes should be only occur in react native code which I mentioned in the bottom of this text.
router.post('/lodge-complaint', verifyToken, verifyCustomer, async (request, response) => {
const pool = await poolPromise;
try {
pool.request()
.input('_customerEmail', sql.VarChar(50), request.payload.username)
.input('_productID', sql.Int, request.body.productID)
.input('_description', sql.VarChar(5000), request.body.productID)
.execute('lodgeComplaint', (error, result) => {
if (error) {
response.status(500).send({
status: false
});
} else {
console.log(JSON.stringify(result) + ' 75 admin.js');
response.status(200).send({
status: true
});
}
});
} catch (e) {
response.status(500).send({status: false});
}
});
And My react native form is:
import * as React from 'react';
import {Button, View, Text, ScrollView, StyleSheet} from 'react-native';
import {Appbar} from 'react-native-paper';
import {TextInput, HelperText} from 'react-native-paper';
import {useState , useEffect} from 'react';
import Axios from 'axios';
import {complaintSubmission} from '../../services/complaint-submissionService';
const ComplaintSubmission = ({navigation}) => {
const [productID , setproductID] = useState("")
const [complaintSubject , setcomplaintSubject] = useState("")
const [description , setdescription] = useState("")
return (
<ScrollView>
<Appbar.Header>
<Appbar.BackAction onPress={() => navigation.openDrawer()} />
<Appbar.Content title="Submit Complaint" />
<Appbar.Action icon="magnify" onPress={() => navigation.openDrawer()} />
</Appbar.Header>
<Text>Plese Fill the following</Text>
<View>
<TextInput
style={styles.PIDstyle}
label="Product ID"
onChange={ (e) =>{
setproductID(e.target.value)
}}
// value={text}
/>
<HelperText type="error">
{/*<HelperText type="error" visible={hasErrors()}>*/}
Product ID Required
</HelperText>
</View>
<TextInput
style={styles.PIDstyle}
label="Description"
onChange={ (e) =>{
setdescription(e.target.value)
}}
// value={text}
/>
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text>This is submittion</Text>
<Button onPress={() => } title="Submit Complaint" />
</View>
</ScrollView>
);
};
export default ComplaintSubmission;
const styles = StyleSheet.create({
PIDstyle: {
marginTop: 30,
marginLeft: 10,
marginRight: 10,
},
});
What is the function I need to implement in React native code.
Create a new function inside your component, something like handleSubmit() and inside use axios (or fetch) to send the information to the backend, that new function should be called here <Button onPress={() => handleSubmit()} title="Submit Complaint" />.
Please see this tutorial for axios: https://blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/
The function should be like:
const handleSubmit = async () => {
const response = await axios({
method: 'post',
url: '/login',
data: JSON.stringify({
complainid: complainid,
Description: description
}));
// Handle the response
}
Related
Console logging my react native app shows the data I fetch from an API. The problem now is that it is not displaying in the FlatList.
const HealthLinkMain = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(API_URL, {
method: "GET",
headers: {
Authorization: `Bearer ${TOKEN}`,
},
});
setData(response.data)
} catch (error) {
console.error(error);
}
};
fetchData();
}, []);
return (
<View style={styles.container}>
<Text>Test</Text>
<FlatList
data={data.data}
renderItem={(item) => (
<View>
<Text>{item.clinic_name}</Text>
<Text>{item.clinic_address}</Text>
</View>
)}
keyExtractor={(item, index) => item.clinic_name}
/>
</View>
);
};
I think the problem might be in your renderItem as you haven't destructured the item, try this:
renderItem = {({ item }) => {
return (
<View>
<Text>{item.clinic_name}</Text>
<Text>{item.clinic_address}</Text>
</View>
)
}}
You can also seperate it the renderItem into a function of it's own which a lot of people tend to do:
const renderItem = ({item}) => {
return(
<View>
<Text>{item.clinic_name}</Text>
<Text>{item.clinic_address}</Text>
</View>
)
}
and then change the flatlist calling function accordingly:
<FlatList
data={data.data}
renderItem={renderItem}
keyExtractor={(item, index) => item.clinic_name}
/>
How can I fetch data from Firebase Realtime Database using the below method?
My Realtime Database:
import React, { useEffect, useState, useContext, } from 'react';
import { View, Text, Image, StyleSheet, ScrollView, SafeAreaView, ActivityIndicator, FlatList, } from 'react-native';
import {firebase} from '../config';
export default function App() {
const [users, setUsers] = useState([]);
const todoRef = firebase.firestore().collection('testing');
useEffect(() => {
todoRef.onSnapshot(
querySnapshot => {
const users = []
querySnapshot.forEach((doc) => {
const { one, two, three, four
} = doc.data()
users.push({
id: doc.id,
one, two, three, four
})
})
setUsers(users)
}
)
}, [])
return (
<View style={{ backgroundColor: theme.viewOne, }}>
{isLoading ? <ActivityIndicator /> : (
<FlatList
ListHeaderComponent={
<Image source={require('./AllImage/qq2.jpg')}
style={{ width: "auto", height: 150, resizeMode: "cover", }} />
}
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<View style={styles.container}>
<View style={styles.item}>
<Text style={styles.mainText}>{item.one}</Text>
</View>
<View style={styles.item}>
<Text style={styles.mainText}>{item.two}</Text>
</View>
</View>
)}
/>
)}
</View>
);
};
Rahul for react-native you can implement it like this instead of using async-await.
You need to connect your app to database like this -
import { firebase } from '#react-native-firebase/database';
const reference = firebase
.app()
.database('https://<databaseName>.<region>.firebasedatabase.app/')
.ref('/users/123');
Then you can perform read-write transactions like this -
import database from '#react-native-firebase/database';
database()
.ref('/users/123')
.once('value')
.then(snapshot => {
console.log('User data: ', snapshot.val());
});
The article has a detailed implementation and you can choose to persist data easily as well. Hope it helps!
I wanted to show a list of data in my app, I already have backend API that can get the data from the server but when I trying to make it appear in my react native app, it wont appear. Below is the data that get from API
here is the code for show the data in a list view in react native apps
import React, { useState, useEffect,Component,onMount} from 'react';
import {View,Text, Button, StyleSheet,TextInput,ListView,ActivityIndicator,Platform} from 'react-native';
import {useNavigation} from'#react-navigation/native';
import {StatusBar} from'expo-status-bar';
export default function StopJob(){
const[isLoading,setIsLoading]=useState(true);
useEffect(()=>{
return fetch('http://localhost/api/findid.php',{
mode:'no-cors'
})
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2)=> r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson),
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
})
},[]);
const Showlist=(user,job,jobid,machinecode,startTime)=>{
this.props.navigation.navigate('Third', {
Userid : user,
Job : job,
JobId : jobid,
MachineCode : machinecode,
StartTime : startTime
});
}
const ListViewItemSeparator = () => {
return (
<View
style={{
height: .5,
width: "100%",
backgroundColor: "#000",
}}
/>
);
}
if(isLoading)return(<View style={{flex: 1, paddingTop: 20}}><ActivityIndicator /> </View>);
return(
<View style={styles.MainContainer_For_Show_StudentList_Activity}>
<ListView
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
renderRow={ (rowData) => <Text style={styles.rowViewContainer}
onPress={this.Showlist.bind(
this, rowData.user,
rowData.job,
rowData.jobid,
rowData.machinecode,
rowData.startTime
)} >
{rowData.job}
</Text> }
/>
</View>
);
}
const styles = StyleSheet.create({
MainContainer_For_Show_StudentList_Activity :{
flex:1,
paddingTop: (Platform.OS == 'ios') ? 20 : 0,
marginLeft: 5,
marginRight: 5
},
rowViewContainer: {
fontSize: 20,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10,
}
});
the expected output will only show the job from the database, but for now the function did not show the list view the error shown Text strings must be rendered within a component.
I was referring this webpage to implement the code : https://reactnativecode.com/insert-update-display-delete-crud-operations/
on the example it show function well but when I try to implement it, it cant work :(
updated but still having same error
export default function StopJob(){
const[isLoading,setIsLoading]=useState(true);
const[dataSource,setdataSource]=useState();
useEffect(()=>{
return fetch('http://localhost/api/findid.php')
.then((response) => response.json())
.then((responseJson) => {
let ds = new FlatList.DataSource({rowHasChanged: (r1, r2)=> r1 !== r2});
setIsLoading(false)
setdataSource(ds.cloneWithRows(responseJson))
})
.catch((error) => {
console.error(error);
})
},[]);
const Showlist=(user,job,jobid,machinecode,startTime)=>{
this.props.navigation.navigate('', {
Userid : user,
Job : job,
JobId : jobid,
MachineCode : machinecode,
StartTime : startTime
});
}
const ListViewItemSeparator = () => {
return (
<View
style={{
height: .5,
width: "100%",
backgroundColor: "#000",
}}
/>
);
}
if(isLoading)return(<View style={{flex: 1, paddingTop: 20}}><ActivityIndicator /> </View>);
return(
<View style={styles.MainContainer_For_Show_StudentList_Activity}>
<FlatList
dataSource={dataSource}
keyExtractor={item=>item.user}
ItemSeparatorComponent= {ListViewItemSeparator()}
renderItem={ (item) => <Text style={styles.rowViewContainer}>{item.job}</Text> }
/>
</View>
);
}
Ok here are the steps to follow:
Use flatlist
Your data source should be a regular array. So, you can use the response from your api as it is.
renderRow should change as renderItem
renderSeparator should change as ItemSeparatorComponent
here is the final form:
const[isLoading,setIsLoading]=useState(true);
const [data, setData]=useState([]);
.......
fetch('http://localhost/api/findid.php',{
mode:'no-cors'
})
.then((response) => response.json())
.then((responseJson) => {
//you can't use setState inside function components. :)
setData(responseJson);
setLoading(false);
})
.catch((error) => {
console.error(error);
})
.......
<FlatList
data={data}
keyExtractor={item => item.jobid} //it should be unique. change it
renderItem={({item}) => <Text>{item.job}</Text>}
/>
This should solve your issue for now but keep in mind these too:
Looks like you don't know differences between class components and function components. Do your research
Flatlist has it's own performance configurations. Research and implement them.
I'm fetching random images from my react application, not from an external API but the content type of the response is in text/Html. how to change it to image/png.
here's my component below as I'm using fetch to make the call for my internal app.
import React, { useState, useEffect } from "react";
import { MapContainer, Marker, Popup, TileLayer } from "react-leaflet";
import L from "leaflet";
import "styles/modules/vehicle/map.scss";
const Map: React.FC<any> = () => {
const [url, setUrl] = useState('')
useEffect(() => {
const headers = { 'Content-Type': 'image/png' }
fetch('/assets/tiles/18/153811/108130.png', { headers })
.then(res => res)
.then(data => setUrl(data.url))
}, [])
const getIcon = (iconSize) => {
return L.icon({
iconUrl: require("assets/images/png/location.png"),
iconSize,
});
};
return (
<div className="map">
<MapContainer
center={[30.02161, 31.25146]}
zoom={18}
scrollWheelZoom={false}
style={{ width: "100%", height: "100%" }}
>
<TileLayer url={url} />
<Marker position={[30.02161, 31.25146]} icon={getIcon(60)}>
<Popup>
A pretty CSS3 popup. <br /> customizable.
</Popup>
</Marker>
</MapContainer>
</div>
);
};
export default Map;
I am currently making an IoT App that I'm trying to connect to a raspberry pi using MQTT. I use the react_native_mqtt package. I use the code posted by simaAttar from here: How to use MQTT on React Native? . The problem I have it doesnt always update my code when I alter it and save. What I'm trying to achieve is to receive a JSON formatted string from the rasp and use that to fill a FlatList with react-native-elements ListItem. But the data received is undefined, even though yesterday I did have it working for a second, it won't work anymore now.
Any help is appreciated.
EDIT: this is the code (forgot to post it)
import React, {Component} from 'react';
import init from 'react_native_mqtt';
import AsyncStorage from '#react-native-community/async-storage';
import {
ActivityIndicator,
StyleSheet,
Text,
View,
FlatList,
TouchableOpacity,
TextInput,
Button,
Alert,
} from 'react-native';
import {ListItem} from 'react-native-elements';
init({
size: 10000,
storageBackend: AsyncStorage,
enableCache: true,
sync: {},
});
export default class AllPeople extends Component {
constructor() {
super();
this.onMessageArrived = this.onMessageArrived.bind(this);
this.onConnectionLost = this.onConnectionLost.bind(this);
const client = new Paho.MQTT.Client(
'onto.mywire.org',
8080,
'Client-' + Math.random() * 9999 + 1,
);
client.onMessageArrived = this.onMessageArrived;
client.onConnectionLost = this.onConnectionLost;
client.connect({
onSuccess: this.onConnect,
useSSL: false,
onFailure: (e) => {
console.log('Error: ', e);
},
});
this.state = {
message: [''],
data: [],
isLoading: true,
client,
messageToSend: '',
isConnected: false,
};
}
onConnect = () => {
console.log('Connected');
const {client} = this.state;
client.subscribe('/app/to/allpeople');
this.setState({
isConnected: true,
error: '',
isLoading: true,
messageToSend: 'allpeople',
});
this.sendMessage();
};
onMessageArrived(entry) {
console.log("Nieuwe Test 1:")
console.log("PayloadMEssage: "+entry.payloadMessage);
console.log("Payload tostring: "+entry.payloadMessage.toString())
//this.setState({data: entry, isLoading: false});
}
sendMessage = () => {
console.log('message send.');
var message = new Paho.MQTT.Message(this.state.messageToSend);
message.destinationName = '/app/from';
if (this.state.isConnected) {
this.state.client.send(message);
} else {
this.connect(this.state.client)
.then(() => {
this.state.client.send(message);
this.setState({error: '', isConnected: true});
})
.catch((error) => {
console.log(error);
this.setState({error: error});
});
}
};
onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log('onConnectionLost:' + responseObject.errorMessage);
this.setState({error: 'Lost Connection', isConnected: false});
}
}
render() {
return (
<View style={styles.container}>
{this.state.isLoading ? (
<ActivityIndicator />
) : (
<FlatList
keyExtractor={keyExtractor}
data={this.state.data}
renderItem={Item}
/>
)}
</View>
);
}
}
const keyExtractor = (item, index) => login.username.toString();
const Item = ({item}) => {
return (
<TouchableOpacity>
<ListItem
title="TestTitle" //{item.results.name.first}
titleStyle={{fontWeight: 'bold'}}
leftIcon={<MCIcons name="account" size={36} color="dodgerblue" />}
subtitle={item.results.name.last}
rightTitle={item.results.registered.date}
rightTitleStyle={{fontSize: 14}}
chevron
bottomDivider
/>
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
container: {
backgroundColor: '#F5FCFF',
},
});
I have managed to fix it by changing entry.payloadMessage to entry.payloadString. Apparentyly I changed it during the editing of my code.