This is my MapView code,
<MapView
style={styles.map}
initialRegion={
this.state.region
}
region={this.state.region}
onRegionChangeComplete={this.onRegionChange}
showsMyLocationButton
showsCompass
showsUserLocation
zoomControlEnabled
loadingEnabled
onMapReady={this.state.placesread ? this.getBreakfast : null}
>
{marker}
</MapView>
My problem is when user moves the map position the map starts randomly moving around without stopping, and it cannot be stopped without closing the map window.
when the map loads i get markers and load on the map and similar to google maps i have a search this area button on the map, i am using the onRegionChangeComplete to store the new region to state.
my onRegionChangeComplete code is,
onRegionChange = async region => {
await this.setState({ region });
await this.setState({ regionChange: true });
};
I guess the problem is that you are using onRegionChangeComplete callback to store the new region to state. i.e this.state.region. and that region prop is passed to MapView Component.
Try removing region={this.state.region} from MapView component.
Update
Also one more thing using await with setState is totally redundant(await this.setState({ region })) because setSate does not return promise but undefined.
setState is asynchronous function. If you want to await it what you can do is you can put it into a promise and resolve in callback/second argument.
For Example whenever you want setState to behave as synchronous call promisedSetState like so.
promisedSetState = (newState) => new Promise((resolve) => {
this.setState(newState, () => {
resolve();
});
});
//await the promise to get resolved
await promisedSetState({newState: 'whatever it is'});
Related
Here is my sample React component:
const OwnerView = () => {
const [monthlyCharge, setMonthlyCharge] = useState(0)
useEffect(() => {
getPerMonthCharges(ownerPhoneNumber, vehicles.length)
}, [])
async function getPerMonthCharges(ownerPhoneNumber, noOfCars) {
console.log(`inside getPerMonthCharges`);
try {
const serviceProviderChargesDoc = await firestore().collection(`${serviceProviderId}_charges`).doc(`${ownerPhoneNumber}`).get()
if (serviceProviderChargesDoc?.data()?.chargesPerMonth > 0) {
setMonthlyCharge(serviceProviderChargesDoc?.data()?.chargesPerMonth)
return
}
} catch (error) {
console.log(`Error while fetching monthly charge ${error}`);
}
setMonthlyCharge(noOfCars * perMonthGeneralCharge)
console.log(`done with getPerMonthCharges`);
}
}
There is a possibility that OwnerView gets unmounted even before getPerMonthCharges() completes its execution. Therefore in case OwnerView gets unmounted I receive a warning that am doing state update on an unmounted component and this is a non-op. Can someone please highlight what is your observation and right way to write this piece of code?
There are many ways to address this
You can check if the component is still Mounted, a bit ugly approach I agree, but quite a standard one (I would just use something like useAsync from react-use, which essentially does the same, but hides the ugliness)
Move loading logic outside of UI and make part of the global state (Redux, MobX, Apollo, or any other state management library), it would be in lines of separation of concerns and should make your code more readable.
The worst would be to prevent your user from any actions, while content is loading - making your app seem clunky, but React would not complain anymore.
The closest to the right way would be 2, but this can sparkle religious debates and some witch-burning, which I'm not a fan of.
You can refer to this: https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup
You can have a variable to keep track whether your component has unmount, let isMounted = true inside useEffect and set it to false as soon as the component is unmounted.
The code will be:
useEffect(() => {
let isMounted = true;
async function getPerMonthCharges(ownerPhoneNumber, noOfCars) {
console.log(`inside getPerMonthCharges`);
try {
const serviceProviderChargesDoc = await firestore().collection(`${serviceProviderId}_charges`).doc(`${ownerPhoneNumber}`).get()
if (serviceProviderChargesDoc?.data()?.chargesPerMonth > 0 && isMounted) { // add conditional check
setMonthlyCharge(serviceProviderChargesDoc?.data()?.chargesPerMonth)
return
}
} catch (error) {
console.log(`Error while fetching monthly charge ${error}`);
}
if (isMounted) setMonthlyCharge(noOfCars * perMonthGeneralCharge) // add conditional check
console.log(`done with getPerMonthCharges`);
}
getPerMonthCharges(ownerPhoneNumber, vehicles.length)
return () => { isMounted = false }; // cleanup toggles value, if unmounted
}, []);
I have big problem with my first React Native app. I've spend few hours today to find the solution but unfortunately nothing helps me.
I have two views:
<Router>
<Stack>
<Scene key="objectsList"
component={ ObjectsList } title="Objects"
onRight={() => Actions.addObject()} rightTitle="Add object" />
<Scene key="addObject" component={ AddObject } title="Add" />
</Stack>
</Router>
First view is a FlatList that is displaying data loaded from AsyncStorage. User can add new object by pressing the right button Add object on the navigation bar. AddObject Scene will be present on the screen. There is another FlatList with some options. User can tap on the cell and then the data is save to the AsyncStorage and after that I call Actions.pop(); function.
The view is gone but I couldn't refresh first screen Objects to reload data and display new value. I've tried a lot solutions from git, stackoverflow and other forums. Nothing works for me.
I am using react-native-router-flux for routing.
I will be glad for help or example code because I am stuck on this problem and it block my project.
P.S. I want to refresh view, send new props or do something that will not reload whole Component. There is a map on it and if I am reloading whole View it is loading from the beginning. I want only to inform that there is some change and run some function to refresh it.
EDIT:
After implemented the solution proposed by Phyo unfortunately I couldn't refresh the data in proper way. When user choose something on AddObject scene he comes back to first view but nothing happened. The change is implemented after user open AddObject scene second time. The function from props is running only when scene 2 is appear again.
My second attempt looks like that:
ObjectsList
state = { selectedObject: "" }
componentDidMount() {
this.loadSelectedObject();
}
refreshState() {
this.loadSelectedObject();
}
loadSelectedObject() {
AsyncStorage.getItem('ObjectKey', (err, object) => {
if (object) {
this.setState({ selectedObject: object })
}
});
}
render() {
return(
<Button onPress={() => Actions.addObject({onBack: refreshState()})}>
);
}
Add Object
onPressItem = (object) => {
AsyncStorage.setItem('ObjectKey', object, () => {
this.props.onBack;
Actions.pop();
});
};
render() {
return (
<FlatList
data={this.state.objects}
keyExtractor={(item, index) => item}
key={this.state.numColumns}
numColumns={this.state.numColumns}
renderItem={(data) =>
<LineCell onPressItem={this.onPressItem} object={String(data.item.object)} />
);
}
I found a solution with friend's help. The code:
ObjectsList
state = { selectedObject: "" }
componentDidMount() {
this.loadSelectedObject();
}
refreshState() {
this.loadSelectedObject();
}
loadSelectedObject() {
AsyncStorage.getItem('ObjectKey', (err, object) => {
if (object) {
this.setState({ selectedObject: object })
}
});
}
render() {
return(
<Button onPress={() => Actions.addObject()}>
);
}
Add Object
onPressItem = (object) => {
AsyncStorage.setItem('ObjectKey', object, () => {
Actions.pop();
Actions.refs.objectsList.refreshState(); //Solution
});
};
On your first view, create a function e.g., refreshFirstView() and pass that function to the second view.
On your second view, call that function this.props.refreshFristView() before you called Actions.pop()
In your refreshFirstView() on the first view, simply call all the function you called to retrieve from AsyncStorage.
First View
componentDidMount(){
retrieveAsynStorageItems()
doSomeOtherLikeFilteringOrSorting()
}
refreshFirstView(){
retrieveAsynStorageItems()//by calling this func again you will get newly saved item
doSomeOtherLikeFilteringOrSorting()
}
I hope this is what you need.
I have the react-native map running with google for both IOS and Android.
Is there a way to have the mapType layer switcher like that of google maps app enabled in react-native expo app? So that user can switch mapTypes (standard, satellite, ....)
a simplified version of the code
constructor(props) {
super(props);
this.state = {
mapRegion: null,
markers: [],
mapType: null
};
}
switchMapType() {
console.log('Changing');
this.state.mapType = 'satellite'
}
render() {
return (
<MapView
provider="google"
mapType={this.state.mapType}
>
<Icon
onPress={this.switchMapType}
/>
</MapView>
);
}
I get an undefined error when inside state switchMapType().
Looking at the documentation it can be as simple as passing the correct style to the mapType prop
https://github.com/react-native-community/react-native-maps/blob/master/docs/mapview.md
The map type to be displayed.
standard: standard road map (default)
none: no map
satellite: satellite view
hybrid: satellite view with roads and points of interest overlayed
terrain: (Android only) topographic view
mutedStandard: more subtle, makes markers/lines pop more (iOS 11.0+ only)
Binding you function
You are getting that error because probably need to bind your function so that it knows that value of this to use. You can do it in your constructor by putting the following in your constructor
constructor(props) {
...
this.switchMapType = this.switchMapType.bind(this);
...
}
or you could convert switchMapType to an arrow function by changing its declaration to
switchMapType = () => {
...
}
or you could bind the function when you call it
<Icon
onPress={this.switchMapType.bind(this}
/>
You can see this article for more details https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56
I prefer to use arrow functions myself.
Setting State
I also notice that there is an error in your function switchMapType with how you are setting state. You are calling this.state.mapType = 'satellite' You should not manipulate state like this. Changing state like this will not force a re-render (which is what you want) and it can lead to unexpected consequences. See this article for more on setting state https://medium.com/#baphemot/understanding-reactjs-setstate-a4640451865b
If you want to change the state you should use this.setState({ key1: value1, key2, value2 });
So if you update your switchMapType function to be the following it should work
switchMapType = () => {
console.log('changing');
this.setState({ mapType: 'satellite' });
}
If you want to be able to toggle between the satellite and standard versions you could do something like this. This uses a ternary statement to handle the if/else https://codeburst.io/javascript-the-conditional-ternary-operator-explained-cac7218beeff
switchMapType = () => {
console.log('changing');
this.setState({ mapType: this.state.mapType === 'satellite' ? 'standard' : 'satellite' });
}
I'm currently fiddling around with react-native-maps to simulate various moving objects around a map space (simulating real time tracking of items) with a callout showing each object's name beside the marker denoting it.
I'm currently able to show the callout for each marker whenever I press it. However, what I intend to do is create a button which toggles on or off the callouts for every marker on the map.
I'm currently using the react-native-maps library for my map.
What I've done are as such:
/* this.props.trackedObjects is an array of objects containing
coordinate information retrieved from database with the following format
trackedObjects=[{
coordinate:{
latitude,
longitude
},
userName
}, ...]
*/
/* inside render() */
{this.props.trackedObjects.map((eachObject) => (
<View>
<MapView.Marker
ref={ref => {this.marker = ref;}}
key={eachObject.userName}
coordinate={eachObject.coordinate}
>
/*Custom Callout that displays eachObject.userName as a <Text>*/
</MapView.Marker>
</View>
))}
/* Button onPress method */
onPress(){
if(toggledOn){
this.marker.showCallout();
}else{
this.marker.hideCallout();
}
}
It seems that when I render a single Marker component, this method works. However, I can't quite crack my head to get around using showCallout() to show the callouts for an entire group of markers.
Would anyone be able to shed some light on how to go about doing this?
1. Wrap the component MapView.Marker into a custom Marker:
class Marker extends React.Component {
marker
render () {
return (
<MapView.Marker {...this.props} ref={_marker => {this.marker = _marker}} />
)
}
componentDidUpdate (prevProps) {
if (prevProps.calloutVisible !== this.props.calloutVisible) {
this.updateCallout();
}
}
updateCallout () {
if (this.props.calloutVisible) {
this.marker.showCallout()
} else {
this.marker.hideCallout()
}
}
}
2. Update your higher level component accordingly in order to provide the callout visibility filter via prop calloutVisible:
/* inside render() */
{this.props.trackedObjects.map((eachObject) => (
<View>
<Marker
key={eachObject.userName}
coordinate={eachObject.coordinate}
calloutVisible={eachObject.calloutVisible} // visibility filter here
>
/*Custom Callout that displays eachObject.userName as a <Text>*/
</MapView.Marker>
</View>
))}
I'm trying to get the initial position of the app at x:(device.width*2) since the app consist of 3 main views, yet it doesn't seem to move even with the animation delay, it start on the left view.
componentDidMount() {
const offset = window.width * this.props.initialIndex;
InteractionManager.runAfterInteractions(() => {
this._scrollView.scrollTo({x:offset, animated: false});
})
}
I also tried with Interaction Manager, but i don't know why it doesn't work; setting a timeout worked for me.
setTimeout(() => {
this.scrollView.scrollTo(cordenates, animated);
}, 0);