Iam using fetch API to show Flatlist data in my screen.
Here is the Json data that i am getting
{
"requestDetails": "facilityList",
"data": [
{
"facilityId": 73,
"name": "ALS-ALL SAINTS HOSPITAL-NTX",
"facilitY_PFX": "ALS",
"isFromAllScripts": false
},
{
"facilityId": 74,
"name": "BHVH-BAYLOR HEART AND VASCULAR HOSPITAL-NTX",
"facilitY_PFX": "BHVH",
"isFromAllScripts": false
},
{
"facilityId": 78,
"name": "BUMC-BAYLOR UNIVERSITY MEDICAL CENTER HOSPITAL-NTX",
"facilitY_PFX": "BUMC",
"isFromAllScripts": false
},
{
"facilityId": 79,
"name": "CAR-CARROLLTON HOSPITAL-NTX",
"facilitY_PFX": "CAR",
"isFromAllScripts": true
},
{
"facilityId": 81,
"name": "DEN-TEXAS HEART HOSPITAL BAYLOR DENTON-NTX",
"facilitY_PFX": "DEN",
"isFromAllScripts": true
},
]
Here is my code
import React from 'react';
import { ActivityIndicator, Text, View, StyleSheet, TouchableOpacity, FlatList } from 'react-native';
interface IState {
isLoading: boolean;
dataSource: any;
}
export default class FacilityList extends React.Component<{}, IState> {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: [],
};
this.renderItem = this.renderItem.bind(this);
}
componentDidMount() {
return fetch(Request_url)
.then((response) => response.json())
.then((responseJson) => {
// just setState here e.g.
this.setState({ dataSource: responseJson.data, isLoading: false });
})
.catch((error) => {
console.error(error);
});
}
renderItem = ({ item }) => {
return (
<View >
<Text >{item.name}</Text>
</View>
);
}
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.dataSource}
renderItem={this.renderItem}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
alignContent: 'center',
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
},
touchButton: {
alignSelf: 'center',
backgroundColor: '#2980b9',
paddingVertical: 25,
width: 295,
margin: 15,
},
touchButtonText: {
textAlign: 'center',
color: '#ffffff',
fontWeight: 'bold'
},
});
but nothing is displaying in my screen with this code, i am getting a blank screen
please let me know if there is anything wrong in my code and why the data is not getting displayed without any errors.
Update:
I am sorry, i have to pass a token in the header, after passing the token it was working fine.
Try this snippet.
var newData = "{\"requestDetails\": \"facilityList\",\"data\": [{\"facilityId\": 73,\"name\": \"ALS-ALL SAINTS HOSPITAL-NTX\",\"facilitY_PFX\": \"ALS\",\"isFromAllScripts\": false},{\"facilityId\": 74,\"name\": \"BHVH-BAYLOR HEART AND VASCULAR HOSPITAL-NTX\",\"facilitY_PFX\": \"BHVH\",\"isFromAllScripts\": false}]}";
var jsonObj = JSON.parse(newData);
console.log(jsonObj.data[0].name);
Do you declare Request_url somewhere? or maybe you put a link directly?
Related
React, {useCallback, useState, useEffect, useRef} from 'react';
import {
View,
SafeAreaView,
FlatList,
Image,
Text,
TextInput,
TouchableOpacity,
StyleSheet,
ActivityIndicator,
} from 'react-native';
import Nodata from '../main/banking/common/Nodata';
import Icon from 'react-native-vector-icons/Ionicons';
import Toast from 'react-native-simple-toast';
import axios from 'axios';
import useSessionToken from '../hooks/useSessionToken';
import moment from 'moment';
import ListData from '../main/banking/common/ListData';
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from 'react-native-responsive-screen';
import ShimmerPlaceholder from 'react-native-shimmer-placeholder';
import LinearGradient from 'react-native-linear-gradient';
function CustomerNotes(props) {
const session = useSessionToken();
const textInputRef = useRef();
const [notes, setNotes] = useState('');
const [data, setData] = useState({
notesList: [],
visible: false,
});
useEffect(() => {
getNotes();
}, [session,data]);
const getNotes = async () => {
try {
const qs = require('qs');
let params = qs.stringify({
cust_id: props.customerId,
operation: 'notes_list',
});
await axios
.post(
'https://abc.cdhgfhg.com/adghagsa',
params,
{
headers: {
Cookie: session?.token,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.then(function (response) {
if (response.data.status === 1) {
console.log('customernotes', response.data.data.hits.hits);
setData({
...data,
notesList: response.data.data.hits.hits,
visible: false,
});
}
})
.catch(function (error) {
console.log('CustomerNoteserror', error);
});
} catch (error) {
console.log('CustomerNoteserror', error);
}
};
const renderItem = ({item, index}) => {
var initialtv = Number(index + 1).toString();
var formattedDate = moment(item._source.added_on).format(
'ddd, MMM DD YYYY',
);
// console.log('initial', item, initialtv);
const data = {
text: item._source.notes,
mobile: formattedDate,
amount: '',
};
return <ListData item={data} />;
};
const handleInputSubmit = useCallback(ev => {
const input = ev.nativeEvent.text;
// validate all you want here
setNotes(input);
}, []);
const submitNotes = () => {
if (notes.length > 0) {
setData(prevState => ({
...prevState,
visible: true,
}));
addNotes();
} else {
Toast.show('Enter Notes');
}
};
const addNotes = async () => {
try {
const qs = require('qs');
let params = qs.stringify({
cust_id: props.customerId,
operation: 'add_notes',
notes: notes,
});
await axios
.post(
'https://abc.cdhgfhg.com/adghagsa',
params,
{
headers: {
Cookie: session?.token,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.then(function (response) {
if (response.data.status === 1) {
// console.log('addNotes', response.data);
getNotes();
}
})
.catch(function (error) {
console.log('addNoteserror', error);
});
} catch (error) {
console.log('CustomerNoteserror', error);
}
};
return (
<View style={{flex: 1, backgroundColor: 'white'}}>
{data.visible == true ? (
<ActivityIndicator
size="large"
color="#0096FF"
style={{
justifyContent: 'center',
alignItems: 'center',
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
}}
/>
) : null}
{data.notesList.length != 0 ? (
<FlatList
data={data.notesList}
renderItem={renderItem}
style={{marginTop: hp('1.5%')}}
/>
) : (
<Nodata />
)}
<View
style={{
flex: 1,
flexDirection: 'row',
position: 'absolute',
bottom: 0,
marginBottom: '4%',
}}>
<TextInput
ref={textInputRef}
autoFocus={false}
style={styles.TextInputStyleClass}
placeholder="Write something"
placeholderTextColor={'#D0D0D0'}
onChangeText={
text => setNotes(text)
// (data.notes = text)
}
/>
<TouchableOpacity
onPress={() => submitNotes()}
style={{
height: 44,
width: 46,
backgroundColor: '#0096FF',
borderRadius: 6,
justifyContent: 'center',
alignItems: 'center',
elevation: 5,
marginRight: '4%',
}}>
<Icon
name={'send'}
size={20}
color="#ffffff"
style={{alignItems: 'center', justifyContent: 'center'}}
/>
</TouchableOpacity>
</View>
</View>
);
}
export default React.memo(CustomerNotes);
const styles = StyleSheet.create({
TextInputStyleClass: {
height: 45,
borderColor: '#0096FF',
flex: 7,
marginLeft: '4%',
marginRight: '4%',
flex: 1,
borderRadius: 6,
borderWidth: 1,
paddingLeft: 12,
fontFamily: 'Poppins-Medium',
fontSize: 14,
backgroundColor: 'white',
},
titleStyle: {
fontSize: 13,
color: '#000000',
fontFamily: 'Poppins-SemiBold',
},
subTitle: {
fontSize: 11,
fontFamily: 'Poppins',
color: '#000000',
},
});
I am fetching data from getNotes() API to render in Flatlist also I have a textinput at the bottom of the page. Whenever I submit textinput data to addNotes API data is added sucessfully and again I am calling getNotes API to reload the data in flatlist.
The issue is data rendering in flatlist is getting very slow and also the activityIndicator is not loading properly. When I call submitNotes the activityIndicator should start loading once the data is added and finished data rendering in flatlist the activityloader should stop loading.
To reload the flatlist each time the data changes you can pass extraData props. For performance optimizations, you can limit the number of items to be loaded at once using initialNumToRender, and onScroll more items will be loaded. Toggle refreshing props to true/false based on API response.
<FlatList
data={data.notesList}
renderItem={renderItem}
style={{marginTop: hp('1.5%')}}
keyExtractor={...}
extraData={data.noteList}
initialNumToRender={10}
refreshing={true}
/>
I am new to react-native. I have a flatlist, that takes data from "state". This works. Then, I added a new function in order to add new data to the flatlist (additionally to the existing data).
As soon as I click on the "delete" button ( don't mind the name) the data of the flatlist is being deleted completely. I want the output to be like
Object 1
Object 2
Object 3 (has been added after button click)
What am I doing wrong? Can you please explain me the reason?
EDIT: I get this warning, but no error.
VirtualizedList: missing keys for items, make sure to specify a key or
id property on each item or provide a custom keyExtractor.,
import React, { Component } from "react";
import { Text, View, StyleSheet, Button, FlatList } from "react-native";
class App extends Component {
state = {
counter: 0,
initialElements: [
{ id: "0", text: "Object 1" },
{ id: "1", text: "Object 2" },
],
};
render() {
const currentCounter = this.state.counter;
const exampleState = this.state.initialElements;
const addElement = () => {
let newArray = [...exampleState, { id: "2", text: "Object 3" }];
this.setState({
initialElements: [newArray],
});
};
return (
<View style={styles.container}>
<View style={styles.counter}>
<Text style={styles.textStyle}>{currentCounter}</Text>
</View>
<View style={styles.deleteButton}>
<Button
title="Hello"
onPress={() =>
this.setState({
counter: currentCounter + 1,
})
}
></Button>
<View style={styles.space}></View>
<Button title="Delete" onPress={addElement}></Button>{" "}
{/* as soon as I click here, the content of the list is being deleted */}
</View>
<FlatList
style={styles.listStyle}
key={(item) => item.id}
data={exampleState}
renderItem={(item) => <Text>{item.item.text}</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#fff",
justifyContent: "center",
flex: 1,
flexDirection: "column",
alignItems: "center",
},
counter: {
flexDirection: "row",
justifyContent: "center",
},
deleteButton: {
flexDirection: "row",
margin: 5,
marginTop: 100,
},
space: {
width: 5,
height: 5,
},
textStyle: {
margin: 80,
fontSize: 100,
},
listStyle: {
flexDirection: "column",
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
});
export default App;
I fixed it by changing the addElement to function to:
const addElement = () => {
var newArray = [...exampleState, {id : 2, text : "Object 3"}];
this.setState( {
initialElements: newArray
});
}
So, basically I changed
initialElements: [newArray]
to
initialElements: newArray
because newArray is already an Array, so no need to wrap it again.
I have an array off Object inside a variable named data.
The array looks like this:
const data = [
{
"id": "0.804802585702977",
"value": "Bar",
},
{
"id": "0.9359341974615858",
"value": "Mar",
},
{
"id": "0.4182922963461958",
"value": "Naba",
},
{
"id": "0.6132336648416628",
"value": "Socerr",
},
{
"id": "0.060587558948085984",
"value": "Mall",
},
]
I want to create a search bar to search all the value inside that array and if the search text is equal to the value inside that array the user will be able to see that value?
Please help?
You need to use filter function to search/Sort data from Array. Please check following it may solve you problem.
import React, { useState } from "react";
import { Text, TextInput, View, StyleSheet } from "react-native";
import Constants from "expo-constants";
// 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";
const data = [
{
id: "0.804802585702977",
value: "Bar",
},
{
id: "0.9359341974615858",
value: "Mar",
},
{
id: "0.4182922963461958",
value: "Naba",
},
{
id: "0.6132336648416628",
value: "Socerr",
},
{
id: "0.060587558948085984",
value: "Mall",
},
];
export default function App() {
let [filteredData, setFilteredData] = useState(data);
function _searchFilterFunction(searchText, data) {
let newData = [];
if (searchText) {
newData = data.filter(function(item) {
const itemData = item.value.toUpperCase();
const textData = searchText.toUpperCase();
return itemData.includes(textData);
});
setFilteredData([...newData]);
} else {
setFilteredData([...data]);
}
}
return (
<View style={styles.container}>
<Text style={styles.paragraph}>Search Here.</Text>
<TextInput
style={styles.input}
underlineColorAndroid="transparent"
placeholder="Search"
placeholderTextColor="#9a73ef"
autoCapitalize="none"
onChangeText={(value) => {
_searchFilterFunction(value, data);
}}
/>
{filteredData.map((item, index) => {
return <Text style={styles.paragraph}>{item.value}</Text>;
})}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: Constants.statusBarHeight,
backgroundColor: "#ecf0f1",
padding: 8,
},
input: {
margin: 15,
height: 40,
paddingLeft: 10,
borderRadius: 2,
borderColor: "#7a42f4",
borderWidth: 1,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: "bold",
textAlign: "center",
},
});
I'm using react-native-image-crop-picker to upload multiple images. I have used the following code to do that
ImagePicker.openPicker({
multiple: true
}).then(images => {
this.setState({
avatarSource: images,
});
});
When selected images it will receive this array
[{"height": 1280, "mime": "image/jpeg", "modificationDate": "1572089089000","path": "file:///data/user/0/com.carup/cache/react-native-image-crop-picker/image-ed1c260f-ee73-4ec0-932b-167e9771d24f.jpg",
"size": 199376, "width": 960}]
I have tried to show selected images (in android) with the following code
<Image style={{marginTop:10,height:150, resizeMode:'contain'}} source={{uri:avatarSource.path}}/>
but it will not be showing the images. How can I show selected images?
Here is the answer, used react-native NativeModules.ImageCropPicker instead of react-native-image-crop-picker
import React, {Component} from 'react';
import {
View, Text, StyleSheet, ScrollView, Alert,
Image, TouchableOpacity, NativeModules, Dimensions, StatusBar, SafeAreaView
} from 'react-native';
import {CarColors} from "../assets/Colors";
var commonStyles = require('../assets/style');
var ImagePicker = NativeModules.ImageCropPicker;
export default class App extends Component {
constructor() {
super();
this.state = {
image: null,
images: null
};
}
cleanupImages() {
ImagePicker.clean().then(() => {
// console.log('removed tmp images from tmp directory');
alert('Temporary images history cleared')
}).catch(e => {
alert(e);
});
}
pickMultiple() {
ImagePicker.openPicker({
multiple: true,
waitAnimationEnd: false,
includeExif: true,
forceJpg: true,
}).then(images => {
this.setState({
image: null,
images: images.map(i => {
console.log('received image', i);
return {uri: i.path, width: i.width, height: i.height, mime: i.mime};
})
});
}).catch(e => alert(e));
}
scaledHeight(oldW, oldH, newW) {
return (oldH / oldW) * newW;
}
renderImage(image) {
return <Image style={{width: 200, height: 200, resizeMode: 'contain'}} source={image}/>
}
renderAsset(image) {
if (image.mime && image.mime.toLowerCase().indexOf('video/') !== -1) {
return this.renderVideo(image);
}
return this.renderImage(image);
}
render() {
return (
<SafeAreaView style={styles.safeArea}>
<View style={styles.container}>
<StatusBar
backgroundColor={CarColors.primary}
barStyle="light-content"/>
<TouchableOpacity onPress={this.pickMultiple.bind(this)} style={commonStyles.button}>
<Text style={commonStyles.text}>Select Images</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.cleanupImages.bind(this)} style={commonStyles.button}>
<Text style={commonStyles.text}>Clean History</Text>
</TouchableOpacity>
</View>
<ScrollView style={styles.imgContainer}>
{this.state.image ? this.renderAsset(this.state.image) : null}
{this.state.images ? this.state.images.map(i => <View style={styles.imgView}
key={i.uri}>{this.renderAsset(i)}</View>) : null}
{
this.state.images &&
<TouchableOpacity onPress={this.cleanupImages.bind(this)} style={commonStyles.bottomBtn}>
<Text style={commonStyles.text}>Upload</Text>
</TouchableOpacity>
}
</ScrollView>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: CarColors.white,
},
imgContainer: {
marginVertical: 20
},
button: {
backgroundColor: 'blue',
marginBottom: 10,
},
text: {
color: 'white',
fontSize: 20,
textAlign: 'center'
},
title: {
fontWeight: 'bold',
fontSize: 22
},
safeArea: {
marginTop: 20
},
dateContainer: {
flexDirection: 'row',
},
imgView: {
width: '50%',
marginVertical: 10,
}
});
native i'm trying to swipe to delete a Rdvdetail ( second code )
but when i delete it ,it doesn't disappear from scrollView i have to reopen the page to make it disappear but backside
it works perfectly well i don't how it gonna works to make it disappear
is there any way i could make it disappear immediately from the scrollView ?
by auto reloading the scrollview or filer any help ?
import React, { Component } from "react";
import { ScrollView } from "react-native";
import axios from "axios";
import RdvDetail from "./RdvDetail";
import { CardSection } from "./utilities/CardSection";
import { Spinner } from "./utilities/Spinner";
import Swipeout from "react-native-swipeout";
class Event extends Component {
constructor(props) {
super(props);
this.state = {
Rdvs: [],
rowIndex: null,
refreshing: false
};
}
componentWillMount() {
this.fetchdata();
}
getInitialState = () => {
return {
scrollEnabled: true
};
};
_allowScroll = scrollEnabled => {
this.setState({ scrollEnabled: scrollEnabled });
};
fetchdata = () => {
axios
.get("http://localhost:3000/api/5cc92f1b8929820fecdecda3/mesRdv")
.then(response => this.setState({ Rdvs: response.data }));
};
deleteRdv = id_rdv => {
axios
.delete("http://localhost:3000/api/rdv/" + id_rdv)
.then(response => {
if (response.status === 200) {
console.log(response.data);
}
})
.catch(error => {
console.log(error.response.data.message);
if (error.response.status === 400) {
}
});
};
renderRDV() {
if (this.state.Rdvs.length < 1) {
console.log("here");
return (
<CardSection>
<Spinner size="large" />
</CardSection>
);
} else {
return this.state.Rdvs.map(Rdv => (
<Swipeout
right={[
{
text: "Delete",
backgroundColor: "red",
color: "white",
onPress: () => this.deleteRdv(Rdv._id),
autoClose: true
}
]}
rowIndex={Rdv._id}
sectionId={0}
autoClose={true}
key={Rdv._id}
scroll={event => this._allowScroll(event)}
>
<RdvDetail key={Rdv._id} Rdv={Rdv} />
</Swipeout>
));
}
}
render() {
return (
<ScrollView scrollEnabled={this.state.scrollEnabled}>
{this.renderRDV()}
</ScrollView>
);
}
}
export default Event;
import React, { Component } from "react";
import { Text, View, StyleSheet, TouchableOpacity } from "react-native";
const AlbumDetail = props => {
state = {
rowIndex: null,
monthNames: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
]
};
return (
<View style={styles.container}>
<View style={styles.eventBox}>
<View style={styles.eventDate}>
<Text style={styles.eventDay}>{props.Rdv.day + " "}</Text>
<Text style={styles.eventMonth}>
{this.state.monthNames[props.Rdv.month - 1]}
</Text>
</View>
<View style={styles.eventContent}>
<Text style={styles.eventTime}>{props.Rdv.time}</Text>
<Text style={styles.userName}>{props.Rdv.doctor}</Text>
<Text style={styles.description}>Rdv note</Text>
</View>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
backgroundColor: "#DCDCDC"
},
eventList: {
marginTop: 20
},
eventBox: {
padding: 10,
marginTop: 5,
marginBottom: 5,
flexDirection: "row"
},
eventDate: {
flexDirection: "column"
},
eventDay: {
fontSize: 30,
color: "#0099FF",
fontWeight: "600"
},
eventMonth: {
fontSize: 16,
color: "#0099FF",
fontWeight: "600"
},
eventContent: {
flex: 1,
flexDirection: "column",
alignItems: "flex-start",
marginLeft: 10,
backgroundColor: "#FFFFFF",
padding: 10,
borderRadius: 10
},
description: {
fontSize: 15,
color: "#646464"
},
eventTime: {
fontSize: 18,
color: "#151515"
},
userName: {
fontSize: 16,
color: "#151515"
},
test: {
borderRadius: 20
}
});
export default AlbumDetail;
You could update the Rdvs list in your state state after each delete which would cause the list to re-render. Like this:
deleteRdv = id_rdv => {
axios
.delete("http://localhost:3000/api/rdv/" + id_rdv)
.then(response => {
if (response.status === 200) {
console.log(response.data);
}
this.fetchdata(); // Add this line to fetch new list
})
.catch(error => {
console.log(error.response.data.message);
if (error.response.status === 400) {
}
});
};