I'm currently working on an expo and react-native application and I'm attempting to get some JSON with a latitude and longitude and displaying it as a map marker.
I know there is a lot wrong with the following but I'm struggling greatly to find any documentation for creating GET requests and modifying the information inside of a JSX.element function. Outside of this I'm also not sure how to repeatedly fetch every few minutes in order to continually update this component state
I am sorry if this is basic I am very new to react native and these JSX.element functions not being classes is confusing.
export const Map = (): JSX.Element => (
state = {
responseData: []
}
fetch('https://apiURL', {method: 'GET'})
.then((response) => response.json())
.then((responseJson) => {
this.setState({responseJson})
console.log(responseJson)
})
.catch((error) => {
console.error(error);
});
<MapView
style={styles.map}
loadingEnabled={true}
region={{
latitude: 37.956290,
longitude: -91.779460,
latitudeDelta: 0.015,
longitudeDelta: 0.0121
}}
>
<MapView.Marker
coordinate={{
latitude: responseData.latitude,
longitude: responseData.longitude
}}
title={"Location"}
description={"Location of Location"}
/>
</MapView>
);
I use this Map component within another JSX.element component:
export const MapScreen = (): JSX.Element => (
<SafeAreaView forceInset={{top: 'always'}}>
<Map/>
</SafeAreaView>
);
Turns out I had to remove the JSX.Element statement from the function, and fetch the data from another function.
const useFetch = url => {
const [data, setData] = useState(null);
async function fetchData(){
const response = await(fetch(url))
const json = await response.json();
setData(json);
}
useEffect(() => {
fetchData()
const interval=setInterval(() => {
fetchData()
}, 6000)
return()=>clearInterval(interval)
},[url]);
return data
};
export const Map = () => {
const data = useFetch('APIURL')
if(!data){
return <Text>Loading...</Text>
}
else {
return(
<MapView
style={styles.map}
loadingEnabled={true}
region={{
latitude: 37.956290,
longitude: -91.779460,
latitudeDelta: 0.015,
longitudeDelta: 0.0121
}}
>
<MapView.Marker
coordinate={{
latitude: data.latitude,
longitude: data.longitude
}}
title={"title"}
description={"desc"}
/>
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.