Related
Getting following error when navigating from one screen to another.
E/unknown:ReactNative: TypeError: undefined is not a function
This error is located at:
in F
in Unknown
in Unknown
in Unknown
in RCTView
in Unknown
in RCTView
in Unknown
in RCTView
in Unknown
in Unknown
in RCTView
in Unknown
in k
in Unknown
in PanGestureHandler
in Unknown
in RCTView
in Unknown
in k
in Unknown
in RCTView
in Unknown
in T
in Unknown
in RNSScreen
in k
in Unknown
in o
in Suspense
in Unknown
in q
in l
in s
in Unknown
in RNSScreenContainer
in ScreenContainer
in Unknown
in RCTView
in Unknown
in Unknown
in R
in RNCSafeAreaProvider
in Unknown
in p
in RNGestureHandlerRootView
in Unknown
in S
in Unknown
in u
in Unknown
in Unknown
in Unknown
in Unknown
in Unknown
in Unknown
in Unknown
in Unknown
in RCTView
in Unknown
in RCTView
in Unknown
in y, js engine: hermes, stack:
anonymous#1107:14081
F#1107:13345
Cr#48:43504
Rl#48:55175
Sa#48:96772
vi#48:86899
gi#48:86801
hi#48:86566
oi#48:83486
pt#48:27332
Za#48:79770
al#48:49088
anonymous#562:465
anonymous#598:1424
anonymous#610:748
t#609:296
O#606:521
anonymous#606:750
j#606:575
anonymous#606:730
anonymous#800:9550
tryCallOne#53:15
anonymous#139:26
anonymous#79:1661
k#79:497
w#79:887
callReactNativeMicrotasks#79:3054
value#33:2867
anonymous#33:959
value#33:2503
value#33:918
value#33:853
Above error is showing in android studio while running debug apk on physical device.
My main problem is i am not able to understand where is the error.
Below is my code.
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Image, StyleSheet, StatusBar, SafeAreaView, TouchableWithoutFeedback, TouchableOpacity, Dimensions, TextInput, Animated, ScrollView, FlatList, Linking } from 'react-native';
import { ListItem, Avatar, CheckBox } from 'react-native-elements'
import MapView, { PROVIDER_GOOGLE, Polygon, Marker, LatLng, mapStyle, Polyline, enableLatestRenderer } from 'react-native-maps';
import { useNavigation, useRoute } from '#react-navigation/native';
import MapViewDirections from 'react-native-maps-directions';
import { SvgUri } from 'react-native-svg';
import axios from 'axios';
const API_KEY = 'Key';
enableLatestRenderer();
const PlanewTripmain = ({ navigation: { goBack } }) => {
const route = useRoute();
const [start_latlng, setstart_latlng] = useState('');
const [end_latlng, setend_latlng] = useState('');
const [checked, setChecked] = useState([]);
const [selected, SetSelected] = useState(false)
const [LoginData, setLoginData] = useState([]);
const [TripData, setTripData] = useState(null)
const [Markerer, setMarker] = useState([])
const [locations, setlocations] = useState()
const [Pharmacydetaillist, setPharmacydetaillist] = useState([])
const ref = React.useRef();
const navigation = useNavigation()
const [checkedItems, setCheckedItems] = useState([]);
const myTheme = {
roundness: 4,
colors: {
primary: '#369B5F',
accent: '#D9D9D9',
},
};
const pharmacylist = []
useEffect(() => {
route.params.responseJson[0].data.map((item) => {
//
const data = { "latitude": parseFloat(item.ph_LatLong.split(',')[0]), "longitude": parseFloat(item.ph_LatLong.split(',')[1]) }
polygons.push(data);
const datapList = { ...item, checked: false }
pharmacylist.push(datapList)
});
})
useEffect(() => {
setLoginData(route.params.LoginData.data[0])
setTripData(route.params.responseJson);
setMarker(polygons);
setPharmacydetaillist(pharmacylist)
}, [])
const MyStatusBar = ({ backgroundColor, ...props }) => (
<View style={[styles.statusBar, { backgroundColor }]}>
<SafeAreaView>
<StatusBar translucent backgroundColor={backgroundColor} {...props} />
</SafeAreaView>
</View>
);
const polygons = []
const origin = {
latitude: 41.878114,
longitude: -87.6297778,
};
const destination = {
latitude: 38.6268888,
longitude: -90.1989143,
}
const [checkboxes, setCheckboxes] = useState({
option1: false,
option2: false,
option3: false,
option4: false
});
const handleCheckboxChange = (item) => {
if (checkedItems.includes(item)) {
setCheckedItems(checkedItems.filter((i) => i !== item));
} else {
setCheckedItems([...checkedItems, item]);
}
}
const startTrip = async (actionType) => {
console.log('Start Trip clicked')
const npidata = checkedItems.map((item) => {
return item.ph_NPI;
})
const bodyData = { "start_loc": route.params.responseJson[0].tripdetails[0].startAddress, "end_loc": route.params.responseJson[0].tripdetails[0].endAddress, "start_latlng": route.params.responseJson[1].start_latlng, "end_latlng": route.params.responseJson[1].end_latlng, "trip_name": route.params.responseJson[0].tripdetails[0].tripName, "ph_npi": npidata.join(), "trip_flag": actionType };
fetch(`Api url`, {
method: 'POST',
body: JSON.stringify(bodyData),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${route.params.LoginData.data[0].token}`
}
})
.then((response) => response.json())
.then((responseJson) => {
GetstartTripdetail(responseJson[0].objectUid)
})
.catch((error) => {
console.error(error);
});
};
const GetstartTripdetail = async (objectUid) => {
console.log('GetstartTripdetail clicked')
const bodyDataa = { "objectUid": objectUid };
fetch(`Api url`, {
method: 'POST',
body: JSON.stringify(bodyDataa),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${route.params.LoginData.data[0].token}`
}
})
.then((response) => response.json())
.then((responseJson) => {
const points = responseJson[0].pharmacies.map((item) => {
return { latitude: parseFloat(item.ph_LatLong.split(',')[0]), "longitude": parseFloat(item.ph_LatLong.split(',')[1]) }
})
const origin = { latitude: responseJson[0].startLatLong.split(",")[0], longitude: responseJson[0].startLatLong.split(",")[1] };
const destination = { latitude: responseJson[0].endLatLong.split(",")[0], longitude: responseJson[0].endLatLong.split(",")[1] };
const waypoints = points;
debugger;
navigation.navigate('TripDetail', { responseJson, LoginData })
openMapWithRoute(origin, destination, waypoints);
})
.catch((error) => {
console.error(error);
});
};
const openMapWithRoute = (origin, destination, waypoints) => {
let waypointsString = '';
waypoints.forEach((waypoint) => {
waypointsString += `${waypoint.latitude},${waypoint.longitude}|`;
});
waypointsString = waypointsString.slice(0, -1);
const url = `https://www.google.com/maps/dir/?api=1&origin=${origin.latitude},${origin.longitude}&destination=${destination.latitude},${destination.longitude}&waypoints=${waypointsString}`;
Linking.canOpenURL(url).then(supported => {
if (supported) {
Linking.openURL(url);
} else {
console.log("Don't know how to open URI: " + url);
}
});
};
return (
<View style={[styles.containerPlanned]}>
<MyStatusBar backgroundColor="#2A524B" barStyle="light-content" />
{/* <View style={styles.appBar} /> */}
<View style={styles.headerarea}>
<TouchableWithoutFeedback onPress={() => goBack()}>
<Image
source={require('./assets/images/back_white.png')}
style={styles.menuicon}
/>
</TouchableWithoutFeedback>
<Text style={styles.ongoingtriptxt}>Plan a New Trip</Text>
</View>
{route.params.responseJson != null &&
<>
<View style={styles.MapArea}>
<MapView
provider={PROVIDER_GOOGLE}
style={styles.map}
initialRegion={{
latitude: route.params.responseJson[0].polygonBoundries[5].latitude,
longitude: route.params.responseJson[0].polygonBoundries[5].longitude,
latitudeDelta: 1,
longitudeDelta: 2 * (screenWidth / 291),
}}
>
{/* {locations.map(marker => ( */}
<Polygon
coordinates={route.params.responseJson[0].polygonBoundries}
strokeColor="#f00"
fillColor="rgba(255,0,0,0.2)"
strokeWidth={1}
zIndex={9}
/>
<MapViewDirections
origin={route.params.responseJson[0].tripdetails[0].startAddress}
destination={route.params.responseJson[0].tripdetails[0].endAddress}
apikey={API_KEY}
strokeWidth={1}
strokeColor="#111111"
mode="DRIVING"
/>
{/* ))
} */}
{Markerer.map((markerr, index) => (
<Marker key={index}
coordinate={markerr}
// style={{ width: 13, height: 20 }}
>
<View>
<Image source={require('./assets/images/location.png')}
style={styles.markericon}></Image>
</View>
</Marker>
))}
</MapView>
</View>
<View style={styles.foundpharmacyparent}>
<View style={styles.tripnameparent_box}>
<Text style={styles.tripname}>{route.params.responseJson[0].tripdetails[0].tripName}</Text>
<Text style={styles.editbtn}>Edit Details</Text>
</View>
<View >
<Text style={styles.triplocation}>{route.params.responseJson[0].tripdetails[0].startAddress} - {route.params.responseJson[0].tripdetails[0].endAddress}</Text>
</View>
<View style={styles.noofpharnamebox}>
<Text style={[styles.tripname, styles.size16]}>
{route.params.responseJson[0].tripdetails[0].pharmacyCount} Pharmacies found
</Text>
<TouchableWithoutFeedback>
<Image
source={require('./assets/images/filterbtn.png')}
style={styles.filterbtn}
/>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback>
<Image
source={require('./assets/images/sort_green.png')}
style={styles.menubtn}
/>
</TouchableWithoutFeedback>
</View>
<SafeAreaView>
<ScrollView style={[styles.scrollView, checkedItems.length >= 1 ? styles.scrollViewchecked : ""]}>
{Pharmacydetaillist.map((item, index) => (
<ListItem key={index + 'a'} style={styles.ListItem} containerStyle={{
paddingLeft: 8,
paddingRight: 0,
alignItems: 'flex-start',
backgroundColor: checkedItems.includes(item) ? '#EAF9F0' : 'white',
paddingBottom: 0
}}>
<CheckBox
value={checkedItems.includes(item)}
onValueChange={() => handleCheckboxChange(item)}
checked={checkedItems.includes(item)}
// containerStyle={styles.checkbox}
uncheckedIcon={<Image source={require('./assets/images/unchecked.png')} />}
checkedIcon={<Image source={require('./assets/images/checked.png')} />}
onPress={() => handleCheckboxChange(item)}
/>
{item.logo &&
<View style={styles.avatar}>
<SvgUri
uri={item.logo}
/>
</View>
}
{!item.logo &&
<View style={styles.avatarr}>
<Text style={styles.avatartxt}>{item.pharmacy_Name.split(" ")[0].at(0)}{item.pharmacy_Name.split(" ").slice(-1)[0].at(0)}</Text>
</View>
}
<ListItem.Content style={styles.listitemcontent}>
<View style={styles.Title_parent}>
<Text style={styles.Title}>
{item.pharmacy_Name}
</Text>
</View>
<View style={styles.subtitleView}>
<Text style={styles.from_to_location}>{item.pharmacy_Address}</Text>
<Text style={styles.no_of_visits}>{item.transactions} Transactions . {item.no_Of_Visits} Visits . {item.last_Visit_date}</Text>
</View>
<Text style={{ height: 1, width: "100%", backgroundColor: "#E8E8E8", marginTop: 15 }}></Text>
</ListItem.Content>
</ListItem>
))}
</ScrollView>
</SafeAreaView>
</View>
{checkedItems.length >= 1 &&
<View style={styles.SelectedParent}>
<Text style={styles.selecteditemsboxText}>
{checkedItems.length} Pharmacies Selected
</Text>
<View style={styles.selectedPharbtnParent}>
<TouchableOpacity style={styles.Selectedsavebtn} onPress={() => { startTrip('Created') }
}>
<Text style={styles.SelectedsavebtnText}>Save</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.Selectedstarttripbtn} onPress={() => { startTrip('Started') }
}>
<Text style={styles.SelectedstarttripText}>Start Trip</Text>
</TouchableOpacity>
</View>
</View>
}
</>
}
</View>
);
};
const STATUSBAR_HEIGHT = StatusBar.currentHeight;
const APPBAR_HEIGHT = Platform.OS === 'ios' ? 44 : 56;
const screenWidth = Dimensions.get('window').width;
const screenHeight = Dimensions.get('window').height;
export default PlanewTripmain;
I resolved this issue after going through line by line into my code.
The issue was into this line
<Text style={styles.avatartxt}>{item.pharmacy_Name.split(" ")[0].at(0)}{item.pharmacy_Name.split(" ").slice(-1)[0].at(0)}</Text>
Seems like inline JS not supported in React Native Android.
I am trying to create a Swiggy/Zomato/FoodPanda like the app, I am trying to get user location or set delivery location on to the map.
The issue is happening on Android.
But I am not experiencing a smoothness when moving marker position, especially when zooming in and zooming out.
Map glitches when trying to move pin marker position
please suggest me for improvement and for to get smoothness experience.
I am trying a lot of logic but not getting any desired performance.
Here is my implemented code,
This is my initial setup on constructor
constructor(props) {
super(props);
this.latDelta = 0.00922 * 1.5;
this.longDelta = 0.00421 * 1.5;
this.state = {
visible: false,
address: {},
lastLat: 24.8076793,
lastLong: 93.9360916,
mapRegion: new AnimatedRegion({
latitude: 24.8076793,
longitude: 93.9360916,
latitudeDelta: this.latDelta,
longitudeDelta: this.longDelta
}),
marker: null,
region: new AnimatedRegion({
latitudeDelta: this.latDelta,
longitudeDelta: this.longDelta,
latitude: 24.8076793,
longitude: 93.9360916
}),
autoGeoMarker: {
latitude: 24.8076793,
longitude: 93.9360916,
autoMapAddress: '',
autoMapArea: ''
},
setGeoMarker: {
latitude: 24.8076793,
longitude: 93.9360916,
setMapAddress: '',
setMapArea: ''
},
mapIndicator: false,
mapAddress: '',
mapArea: '',
//-----
indicator: true,
searchModal: false
};
}
componentDidMount() {
this.getPermissionLocation();
}
Here I am asking for permission
getPermissionLocation = () => {
try {
request(
Platform.select({
android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
})
).then(res => {
if (res == 'granted') {
this.setState({
searchModal: false
});
Geolocation.getCurrentPosition(
//Will give you the current location
position => {
let region = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
latitudeDelta: this.latDelta,
longitudeDelta: this.longDelta
};
Alert.alert('', 'Pin Your Delivery point by moving map');
this.setState({
autoGeoMarker: region,
mapIndicator: false,
indicator: false
});
this.onRegionChange(region);
this.getAutoDetectAddress(region.latitude, region.longitude);
},
error => {
//setLocationStatus(error.message);
console.log('error ... 1 ' + error.message);
},
{
enableHighAccuracy: false,
timeout: 30000,
maximumAge: 1000
}
);
} else {
console.log('Location is not enabled');
Alert.alert(
'Enable Your Location:',
'Can not proceed, Please allow your Location permissioin.',
[{ text: 'OK', onPress: () => RNRestart.Restart() }]
);
}
});
} catch (error) {
console.log('location set error:', error);
}
};
//Get Auto Geolocation address
getAutoDetectAddress = (latitude, longitude) => {
Geocoder.from(latitude, longitude)
.then(json => {
let region = {
latitude: latitude,
longitude: longitude,
latitudeDelta: this.latDelta,
longitudeDelta: this.longDelta,
autoMapAddress: json.results[0].formatted_address,
autoMapArea: json.results[0].address_components[1].short_name
};
this.setState({
autoGeoMarker: region
});
})
.catch(error => console.warn(error));
//-----------------------
};
onRegionChange = region => {
this.setState({
region: region,
lastLat: region.latitude,
lastLong: region.longitude
});
this.getAddressInfo(region.latitude, region.longitude);
};
getAddressInfo = (latitude, longitude) => {
Geocoder.from(latitude, longitude)
.then(json => {
this.setState({
mapAddress: json.results[0].formatted_address,
mapArea: json.results[0].address_components[1].short_name
});
let region = {
latitude: json.results[0].geometry.location.lat,
longitude: json.results[0].geometry.location.lng,
latitudeDelta: this.latDelta,
longitudeDelta: this.longDelta,
setMapAddress: json.results[0].formatted_address,
setMapArea: json.results[0].address_components[1].short_name
};
this.setState({
setGeoMarker: region
});
})
.catch(error => console.warn(error));
};
render() {
return this.state.indicator ? (
<View style={{ flex: 1 }}>
<ActivityIndicator size="large" color="#ff6a00" />
</View>
) : (
<View style={{ flex: 1, flexDirection: 'column' }}>
<StatusBar backgroundColor="#ff6a00" />
<View style={styles.map}>
<MapView
style={styles.map}
region={this.state.region}
onRegionChangeComplete={this.onRegionChange}
/>
<View
style={{
flex: 1,
flexDirection: 'row',
alignItems: 'center',
position: 'absolute',
top: '4%',
left: '-3%'
}}
>
<TouchableOpacity
onPress={() => {
{
this.props.navigation.navigate('HomeScreen');
}
}}
>
<Image
style={{ width: 71, height: 51 }}
source={require('../../assets/app/mapback.png')}
/>
</TouchableOpacity>
</View>
<View style={styles.markerFixed}>
<Image style={styles.marker} source={marker} />
</View>
</View>
<View
style={{
flex: 1,
padding: 4,
backgroundColor: '#FFFFFF'
// borderTopColor: 'black',
// borderTopWidth: 1
}}
>
<View
style={{
flex: 1,
flexDirection: 'row',
alignItems: 'center',
marginTop: 15,
marginLeft: 20
}}
>
<View
style={{ flex: 0.8, alignItems: 'center', flexDirection: 'row' }}
>
<Image
style={{ width: 15, height: 20 }}
source={require('../../assets/app/mapmark.png')}
/>
<Text
style={{
fontSize: 18,
marginLeft: 15,
fontFamily: 'Nunito-Black'
}}
>
{this.state.mapArea}
</Text>
</View>
</View>
<Text
style={{
marginTop: 20,
marginLeft: 20,
fontSize: 12,
fontFamily: 'Poppins-Regular'
}}
>
{this.state.mapAddress}
</Text>
</View>
</View>
);
}
here I have doubt where to set these two function properly
this.onRegionChange(region);
this.getAutoDetectAddress(region.latitude, region.longitude);
maybe if these two functions but I am not sure. Where to implement correctly for getting the best performance.
Map glitches or bouncing (While pinching/zooming in and out) issue were caused by using region={this.state.region}
So, I used initialRegion={this.state.region} instead of region
Here is the complete example
onChangeValue = region => {
this.setState({
region
});
Geocoder.from(region.latitude, region.longitude)
.then(json => {
this.setState({
mapAddress: json.results[0].formatted_address,
mapArea: json.results[0].address_components[1].short_name
});
let region = {
latitude: json.results[0].geometry.location.lat,
longitude: json.results[0].geometry.location.lng,
latitudeDelta: 0.021,
longitudeDelta: 0.021,
setMapAddress: json.results[0].formatted_address,
setMapArea: json.results[0].address_components[1].short_name
};
this.setState({
setGeoMarker: region
});
// this.map.animateToRegion(region);
})
.catch(error => console.warn(error));
};
...
<MapView
style={{
flex: 1,
height: Dimensions.get('screen').height / 1.5,
position: 'relative',
marginBottom: this.state.marginBottom
}}
showsUserLocation={true}
initialRegion={this.state.region}
// region={this.state.region}
showsMyLocationButton={true}
onRegionChangeComplete={this.onChangeValue}
ref={ref => (this.map = ref)}
/>
<View
style={{
flex: 1,
flexDirection: 'row',
alignItems: 'center',
position: 'absolute',
top: '4%',
left: '-3%'
}}
>
<TouchableOpacity
onPress={() => {
{
this.props.navigation.navigate('MainTabScreen');
this.props.navigation.navigate('HomeScreen');
}
}}
>
{/*<Icon.MaterialIcons name="arrow-back" size={28} color="black" />*/}
<Image
style={{ width: 71, height: 51 }}
source={require('../../assets/app/mapback.png')}
/>
</TouchableOpacity>
</View>
...
I want save one of views in my react native app as an image to camera roll. I'm using camera roll to save image. I got alert "Image saved successfully" but at the same time on the screen displayed error: " Possible Unhandled Promise Rejection (id: 2): Error: /cacheDir/rn_image_picker_lib_temp_aefbf48e-3b44-461e-a9ec-d51ce0aefb4c.jpg: open failed: ENOENT (No such file or directory)...".
Below I paste code of my UploadScreen class. The image was saved, but the size of file is equal 0 bytes and I can't open it.
Someone could help me?
Thanks in advance
I added dependecy to Android Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is my imported library:
import React from 'react';
import { Text, TextInput, View, Button, Image, ImageBackground, StyleSheet, Alert, PermissionsAndroid } from 'react-native';
import { createAppContainer, StackNavigator } from 'react-navigation';
import { createDrawerNavigator } from 'react-navigation-drawer';
import { createStackNavigator } from 'react-navigation-stack';
import Icon from 'react-native-vector-icons/FontAwesome';
import DialogAndroid from 'react-native-dialogs';
import Sound from 'react-native-sound';
import * as ImagePicker from 'react-native-image-picker';
import CameraRoll from '#react-native-community/cameraroll';
Upload Screen code:
class UploadScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
filepath: {
data: '',
uri: ''
},
fileData: '',
fileUri: ''
}
}
static navigationOptions = ({ navigation }) => ({
headerShown: false
});
showContact = () => {
Sound.setCategory('Playback');
var mySound = new Sound('sound.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('Blad wczytywania: ' + error);
return;
}
else {
mySound.play((success) => {
if (success) {
console.log('Odtwarzanie')
}
})
}
});
mySound.setVolume(1.0);
mySound.release();
}
showDescription = () => {
Sound.setCategory('Playback');
var mySound = new Sound('sound.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('Blad wczytywania: ' + error);
return;
}
else {
mySound.play((success) => {
if (success) {
console.log('Odtwarzanie')
}
})
}
});
mySound.setVolume(1.0);
mySound.release();
Alert.alert('Aplikacja do generowania wlasnych memow', '1. Przeslij swoje zdjecie lub wybierz z jedno z dostepnych. \n 2. Napisz tekst. \n 3. Zapisz utworzony mem. \n\ 4. Udostepnij na swoich social mediach.');
}
selectImage = () => {
let options = {
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.launchImageLibrary(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
alert(response.customButton);
} else {
const source = { uri: response.uri };
console.log('response', JSON.stringify(response));
this.setState({
filePath: response,
fileData: response.data,
fileUri: response.uri
});
}
});
}
takePhoto = () => {
let options = {
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.launchCamera(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
alert(response.customButton);
} else {
const source = { uri: response.uri };
console.log('response', JSON.stringify(response));
this.setState({
filePath: response,
fileData: response.data,
fileUri: response.uri
});
}
});
}
renderImage() {
if (this.state.fileUri) {
return <Image ref="meme" source={{ uri: this.state.fileUri }}
style={{ width: '100%', height: '100%', resizeMode: 'cover' }}
/>
} else {
return <Image ref="meme" source={require('./sources/1.jpg')}
style={{ width: '100%', height: '100%', resizeMode: 'cover' }}
/>
}
}
state = {
top: '',
bottom: '',
};
getPermissionAndroid = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: 'Image Save Permission',
message: 'Your permission is required to save images to your device',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
return true;
}
Alert.alert(
'',
'Your permission is required to save images to your device',
[{ text: 'OK', onPress: () => { } }],
{ cancelable: false },
);
} catch (err) {
console.log('err', err);
}
};
onSaveImage = async () => {
try {
var uri = this.state.fileUri;
console.log(uri);
if (Platform.OS === 'android') {
const granted = this.getPermissionAndroid;
if (!granted) {
return;
}
}
const image = CameraRoll.save(uri, 'photo');
if (image) {
Alert.alert(
'',
'Image saved successfully.',
[{ text: 'OK', onPress: () => { } }],
{ cancelable: false },
);
}
} catch (error) {
console.log('error', error);
}
};
render() {
const { navigate } = this.props.navigation;
const { top, bottom } = this.state;
return (
<View
style={{
flex: 1,
}}>
<ImageBackground style={styles.imgBackground}
resizeMode='cover'
source={require('./sources/background.jpg')}>
<View
style={{
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-end',
}}>
<Icon.Button style={{ right: -4 }}
name="info-circle"
onPress={this.showDescription} >
</Icon.Button>
<Icon.Button style={{ right: -4 }}
name="home"
onPress={() => navigate('Home')}
>
</Icon.Button>
<Icon.Button style={{ right: -6 }}
name="at"
onPress={this.showContact}
>
</Icon.Button>
</View>
<View style={{ flex: 2, alignItems: 'center', justifyContent: 'space-between', }}>
<TextInput underlineColorAndroid={'transparent'} style={styles.input} value={top} onChangeText={(top) => this.setState({ top })} placeholder={'Input top text here'} />
<TextInput underlineColorAndroid={'transparent'} style={styles.input} value={bottom} onChangeText={(bottom) => this.setState({ bottom })} placeholder={'Input bottom text here'} />
</View>
<View style={{ flex: 5, alignItems: 'center', justifyContent: 'space-between', }}>
{this.renderImage()}
<Text style={ styles.memeTop }>{top}</Text>
<Text style={styles.memeBottom}>{bottom}</Text>
</View>
<View style={{ flex: 2, alignItems: 'center', justifyContent: 'space-between', margin: 5}}>
<Button title="Select image file"
onPress={this.selectImage}
/>
<Button title="Take a photo"
onPress={this.takePhoto}
/>
<Button title="Save result"
//onPress={() => navigate('Result')}
onPress={this.onSaveImage}
/>
</View >
<View style={{ flex: 0.3 }}>
<Text style={{
fontFamily: 'Impact', fontWeight: 'bold', fontSize: 10, textAlign: 'right', alignSelf: 'flex-end',
textShadowColor: 'black', textShadowOffset: { width: 10, height: 5 }, textShadowRadius: 10,
color: 'white', position: 'absolute', bottom: 0
}}>
Copyright all right reserved {'\u00A9'} 2021 Marek Przybylowski
</Text>
</View >
</ImageBackground>
</View>
);
}
}
As you can see in the picture above, there is a vertical list of two columns. I have developed two flatLists because I can not style photos with different height on one line with the flatList column option.
I want two flatLists to have the same scroll position.
I wrapped two FlatList component with to synchronize scrolling. But there is a problem here. The scrollView ignores the infinity scroll and calls the pagination objects all at once. There is a performance problem.
How can I solve this problem?
here is my component code
import React from 'react';
import { View, Platfrom, Text, StyleSheet, AsyncStorage, TouchableOpacity, Image, FlatList, Button, Dimensions, ScrollView, ListView } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { NavigationActions } from 'react-navigation';
import { connect } from 'react-redux';
import moment from 'moment';
import * as settings from '../../config/settings';
import Menu from '../menu';
import headerStyles from '../../styles/common/header';
import textStyles from '../../styles/common/text';
import containerStyles from '../../styles/common/container';
import imageStyles from '../../styles/common/image';
import boxStyles from '../../styles/common/box';
import objectStyles from '../../styles/common/object';
import commonStyles from '../../styles/common/common';
import colorStyles from '../../styles/common/color';
const window = Dimensions.get('window');
const styles = StyleSheet.create({
listView: {
paddingTop: 20,
backgroundColor: '#FFFFFF',
},
fullScreen: {
flex: 1,
marginBottom: 50,
},
floatView: {
position: 'absolute',
width: '90%',
marginLeft: '5%',
height: 100,
bottom: -50,
},
});
const phoneWidth = Dimensions.get('window').width
class PurchaseListScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state
return {
title: '중고 명품 구매',
headerStyle: headerStyles.header,
headerTitleStyle: headerStyles.headerTitle,
headerRight: <Icon name="bars" size={30} color="#333" onPress={() => { params.showModal() }} style={{ padding: 10 }} />,
}
}
constructor(props) {
super(props);
this.state = {
user_token: '',
refreshing: false,
isModalVisible: false,
leftColumneData: [],
rightColumneData: [],
leftNextKey: '',
rightNextKey: '',
};
this.hideModal = this.hideModal.bind(this);
}
componentDidMount() {
this.props.navigation.setParams({ showModal: this.showModal });
this.purchaseListService();
}
showModal = () => this.setState({ isModalVisible: true })
hideModal = () => this.setState({ isModalVisible: false })
navigate1 = (item) => {
console.log('click navigate1');
const navigate1 = NavigationActions.navigate({
routeName: "home",
});
this.props.navigation.dispatch(navigate1);
};
purchaseListService = async () => {
if (this.props.isLoggedIn) {
let user_info = await AsyncStorage.getItem('user_info');
get_user_token = JSON.parse(user_info).key;
this.setState({ user_token: get_user_token });
const api_uri1 = settings.base_uri + 'purchase-product/odd/'
const request1 = {
method: 'GET',
headers: {
'Authorization': 'Token ' + get_user_token,
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
const api_uri2 = settings.base_uri + 'purchase-product/even/'
const request2 = {
method: 'GET',
headers: {
'Authorization': 'Token ' + get_user_token,
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
fetch(api_uri1, request1)
.then(res => res.json())
.then(res => {
this.setState({
leftColumneData: [...res.results],
leftNextKey: res.next
})
})
.catch((error) => {
console.error(error);
})
fetch(api_uri2, request2)
.then(res => res.json())
.then(res => {
this.setState({
rightColumneData: [...res.results],
rightNextKey: res.next,
})
})
.catch((error) => {
console.error(error);
})
} else {
const api_uri1 = settings.base_uri + 'purchase-product/odd/'
const request1 = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
const api_uri2 = settings.base_uri + 'purchase-product/even/'
const request2 = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
fetch(api_uri1, request1)
.then(res => res.json())
.then(res => {
this.setState({
leftColumneData: [...res.results],
leftNextKey: res.next,
})
})
.catch((error) => {
console.error(error);
})
fetch(api_uri2, request2)
.then(res => res.json())
.then(res => {
this.setState({
rightColumneData: [...res.results],
rightNextKey: res.next,
})
})
.catch((error) => {
console.error(error);
})
}
}
onEndReachedService = () => {
console.log('run onEndReachedService');
if (this.props.isLoggedIn && this.state.leftNextKey) {
const api_uri1 = this.state.leftNextKey
const request1 = {
method: 'GET',
headers: {
'Authorization': 'Token ' + this.state.user_token,
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
const api_uri2 = this.state.rightNextKey
const request2 = {
method: 'GET',
headers: {
'Authorization': 'Token ' + this.state.user_token,
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
fetch(api_uri1, request1)
.then(res => res.json())
.then(res => {
this.setState({
leftColumneData: [...this.state.leftColumneData, ...res.results],
leftNextKey: res.next
})
})
.catch((error) => {
console.error(error);
})
fetch(api_uri2, request2)
.then(res => res.json())
.then(res => {
this.setState({
rightColumneData: [...this.state.rightColumneData, ...res.results],
rightNextKey: res.next,
})
})
.catch((error) => {
console.error(error);
})
} else if (!this.props.isLoggedIn && this.state.leftNextKey){
const api_uri1 = this.state.leftNextKey
const request1 = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
const api_uri2 = this.state.rightNextKey
const request2 = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
fetch(api_uri1, request1)
.then(res => res.json())
.then(res => {
console.log('update res1', res);
this.setState({
leftColumneData: [...this.state.leftColumneData, ...res.results],
leftNextKey: res.next,
})
})
.catch((error) => {
console.error(error);
})
fetch(api_uri2, request2)
.then(res => res.json())
.then(res => {
console.log('update res2', res);
this.setState({
rightColumneData: [...this.state.rightColumneData, ...res.results],
rightNextKey: res.next,
})
})
.catch((error) => {
console.error(error);
})
}
}
likeService = async (pk, column) => {
let user_info = await AsyncStorage.getItem('user_info');
user_token = JSON.parse(user_info).key;
const api_uri = settings.base_uri + 'purchase-product/' + pk + '/like/'
var request = {
method: 'POST',
headers: {
'Authorization': 'Token ' + user_token,
'Accept': 'application/json',
'Content-Type': 'application/json',
}
};
fetch(api_uri, request)
.then(res => {
if(column=='left'){
var items = this.state.leftColumneData
for (i=0; i<items.length; i++) {
let item = items[i]
if (item.id==pk) {
item.is_liked = !item.is_liked
items[i] = item;
this.setState({ leftColumneData: items })
}
}
} else {
var items = this.state.rightColumneData
for (i = 0; i < items.length; i++) {
let item = items[i]
if (item.id == pk) {
item.is_liked = !item.is_liked
items[i] = item;
this.setState({ rightColumneData: items })
}
}
}
})
.catch((error) => {
console.error(error);
});
}
renderLabel = (text) => {
if (text) {
return (
<View style={{ backgroundColor: 'red', paddingVertical: 2, marginLeft: 3, marginTop: 5, marginBottom: 8, paddingHorizontal: 4 }}>
<Text style={{ color: 'white', fontSize: 9, fontWeight: '400' }}>{text}</Text>
</View>
)
} else {
return (
<View style={{ paddingVertical: 2, marginTop: 5, marginBottom: 8, }}>
</View>
)
}
}
renderList = (item, column) => {
return(
<View>
<View style={{
flex: 1,
borderColor: 'rgb(136, 136, 136)',
borderWidth: 1,
marginLeft: 15,
marginTop: 15,
backgroundColor: 'white',
}}>
<TouchableOpacity onPress={()=>{}}>
{item.is_vertical?
<Image
source={{ uri: item.first_thumbnail }}
style={{ flex:1, height: 210 }}/>
:
<Image
source={{ uri: item.first_thumbnail }}
style={{ flex: 1, height: 130 }} />
}
</TouchableOpacity>
<View style={{ flex: 1 }}>
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity style={{ flex: 4 }}>
<Text style={{
fontSize: 14,
fontWeight: '600',
color: 'rgb(35, 31, 32)',
marginTop: 10,
marginLeft: 8
}}>{item.name}</Text>
<Text style={{
fontSize: 12,
fontWeight: '500',
color: 'rgb(35, 31, 32)',
marginLeft: 8,
marginTop: 8
}}>{item.partner.biz_name}</Text>
<View style={{ flexDirection: 'row', marginLeft: 6 }}>
{this.renderLabel(item.product_type_str)}
{this.renderLabel(item.city.name)}
</View>
</TouchableOpacity>
<View
style={{ flex: 1, marginTop: 10, marginRight: 2, alignItems: 'center' }}>
{this.props.isLoggedIn ?
<View>
{item.is_liked ?
<Icon
name="heart" size={17} color="red"
onPress={() => {
this.likeService(item.id, column);
}} />
: <Icon name="heart-o" size={17} color="red"
onPress={() => {
this.likeService(item.id, column);
}} />
}
</View> :
<View>
<Icon name="heart-o" size={17} color="red"
onPress={() => {
console.log('press heart', column);
}} />
</View>}
</View>
</View>
<View style={[ colorStyles.greenBackground,
{
flex: 1,
borderTopWidth: 1,
borderColor: 'rgb(136, 136, 136)',
padding: 5,
paddingRight: 10,
}]}>
<Text style={{
textAlign: 'right',
fontSize: 14,
fontWeight: '500',
color: 'rgb(35, 31, 32)',
}}>
{(item.price).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}원 {item.id}
</Text>
</View>
</View>
</View>
</View>
)
}
render() {
return (
<View style={{ flex: 1 }}>
<Menu hideModal={this.hideModal.bind(this)} isVisible={this.state.isModalVisible} navigation={this.props.navigation} />
<View style={{ flexDirection: 'row' }}>
<FlatList
style={{ flex: 1 }}
showsVerticalScrollIndicator={false}
initialNumToRender={20}
onEndReachedThreshold={1}
onEndReached={this.onEndReachedService}
refreshing={this.state.refreshing}
onRefresh={this.purchaseListService.bind(this)}
data={this.state.leftColumneData}
renderItem={({ item }) => this.renderList(item, column='left')}
keyExtractor={(item) => item.id}
/>
<FlatList
style={{ flex: 1, paddingRight: 15 }}
showsVerticalScrollIndicator={false}
refreshing={this.state.refreshing}
onRefresh={this.purchaseListService.bind(this)}
data={this.state.rightColumneData}
renderItem={({ item }) => this.renderList(item, column='right')}
keyExtractor={(item) => item.id}
/>
</View>
</View>
)
}
}
const mapStateToProps = state => ({
isLoggedIn: state.loginReducer.isLoggedIn
})
const PurchaseList = connect(mapStateToProps, null)(PurchaseListScreen);
export default PurchaseList;
you can try this code to scroll both flatlist parallelly.
<ScrollView contentContainerStyle={{flexDirection:"row"}}>
<Flatlist
...
scrollEnabled={false}
/>
<Flatlist
...
scrollEnabled={false}
/>
</ScrollView>
Im trying to render a map at the current user geolocation on android device, using react-native maps.
Here is what i've got so far:
import React, { Component } from 'react';
import {
View,
StyleSheet,
Dimensions,
} from 'react-native';
import MapView from 'react-native-maps';
const {width, height} = Dimensions.get('window')
const SCREEN_HEIGHT = height
const SCREEN_WIDTH = width
const ASPECT_RATIO = width / height
const LATITUDE_DELTA = 0.0922
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO
class MapComponent extends Component {
constructor() {
super()
this.state = {
initialPosition: {
latitude: 0,
longitude: 0,
latitudeDelta: 0,
longitudeDelta: 0,
},
}
}
componentDidMount() {
navigator.geolocation.getCurrentPosition((position) => {
var lat = parseFloat(position.coords.latitude)
var long = parseFloat(position.coords.longitude)
var initialRegion = {
latitude: lat,
longitude: long,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}
this.setState({initialPosition: initialRegion})
},
(error) => alert(JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000});
}
renderScreen = () => {
return (
<View style={styles.container}>
<MapView
style={styles.map}
initialRegion={this.state.initialPosition}/>
</View>
);
}
render() {
return (
this.renderScreen()
);
}
}
const styles = StyleSheet.create({
container: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
});
export default MapComponent;
The map renders, but not in current device geolocation, as expected. (it renders in the middle of the ocean)
The permissions are already set at AndroidManifest.xml as:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
After 20 seconds, i get an alert saying, "Location request timed out" "code 3"
What i'm doing wrong?
I'm not sure but there is an issue ("Geolocation timed out, code 3") which looks related
For anyone else struggling with this issue on android, try removing
the maximumAge: 2000 option parameter. This option was causing
geolocation to either timeout or crash the app.
import React, {useState, useEffect} from 'react';
import {StyleSheet, Text} from 'react-native';
import MapView, {Marker} from 'react-native-maps';
import Geolocation from '#react-native-community/geolocation';
const App = () => {
const [position, setPosition] = useState({
latitude: 10,
longitude: 10,
latitudeDelta: 0.001,
longitudeDelta: 0.001,
});
useEffect(() => {
Geolocation.getCurrentPosition((pos) => {
const crd = pos.coords;
setPosition({
latitude: crd.latitude,
longitude: crd.longitude,
latitudeDelta: 0.0421,
longitudeDelta: 0.0421,
});
}).catch((err) => {
console.log(err);
});
}, []);
return (
<MapView
style={styles.map}
initialRegion={position}
showsUserLocation={true}
showsMyLocationButton={true}
followsUserLocation={true}
showsCompass={true}
scrollEnabled={true}
zoomEnabled={true}
pitchEnabled={true}
rotateEnabled={true}>
<Marker
title='Yor are here'
description='This is a description'
coordinate={position}/>
</MapView>
);
};
const styles = StyleSheet.create({
map: {
...StyleSheet.absoluteFillObject,
},
});
export default App;
It's working perfectly in mine. Only change I made was in StyleSheet.
container: {
position: 'absolute',
height : SCREEN_HEIGHT,
width : SCREEN_WIDTH,
justifyContent: 'flex-end',
alignItems: 'center',
}
Thereafter, it renders my location. You can add marker after that to show your location.
This is what worked for me. the third option is what was creating the prob.
navigator.geolocation.getCurrentPosition() =>{
},
err => {
},
{ enableHighAccuracy: false, timeout: 20000}, //this worked for me
navigator.geolocation.getCurrentPosition() is deprecated.
Use #react-native-community/geolocation instead.
npm install #react-native-community/geolocation --save
import React, { Component } from "react";
// global.currentScreenIndex = 'Dashboard';
//Import all required component
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Image,
Modal,
TouchableHighlight,
StatusBar,
FlatList,
ActivityIndicator,
Button,
NetInfo,
} from "react-native";
import MapView, { Marker } from "react-native-maps";
import Geolocation from "#react-native-community/geolocation";
const MyStatusBar = ({ backgroundColor, ...props }) => (
<View style={[styles.statusBar, { backgroundColor }]}>
<StatusBar translucent backgroundColor={backgroundColor} {...props} />
</View>
);
class Dashboard extends Component {
constructor() {
super();
this.state = {
initialPosition: {
latitude: 0,
longitude: 0,
latitudeDelta: 0,
longitudeDelta: 0,
},
};
}
componentDidMount() {
const { navigation } = this.props;
Geolocation.getCurrentPosition((info) => {
let lat = info.coords.latitude;
let long = info.coords.longitude;
console.log(lat);
console.log(long);
var initialRegion = {
latitude: lat,
longitude: long,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
};
this.setState({ initialPosition: initialRegion });
});
}
render() {
const { modalVisible } = this.state;
const { navigate } = this.props.navigation;
// const token_data = token_value();
// console.log("token_homes_2st"+token_data);
return (
<View style={styles.container}>
<MapView
style={styles.map}
initialRegion={this.state.initialPosition}
showsUserLocation={true}
/>
</View>
);
}
}
export default Dashboard;
const styles = StyleSheet.create({
container: {
justifyContent: "center",
fontWeight: "400",
color: "#000",
fontFamily:
"Inter UI,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif",
},
map: {
height: 400,
width: 400,
justifyContent: "flex-end",
alignItems: "center",
},
});
1.npm install #react-native-community/geolocation --save
2.import Geolocation from '#react-native-community/geolocation'; 3.navigator.geolocation.getCurrentPosition => Geolocation.getCurrentPosition