I am building an application using React Native, and I want to use data from Heroku api. But when I make an API call and consolog the data I can see the data, but when I try to map them, nothing is coming out of the DOM. Can anyone tell me what I am doing wrong? Thank you so much. Here below are my can and a screenshop.
App.jsx:
import react, { useEffect, useState } from "react";
import { FlatList, useWindowDimensions, View, Text } from "react-native";
import axios from "axios";
const App = () => {
const { height } = useWindowDimensions();
const [places, setPlaces] = useState({});
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
useEffect(() => {
axios
.post(
"https://where2playdk.herokuapp.com/nearest?lat=55.70232019168349&lon=12.561693791177802"
)
.then((response) => console.log(response.data))
.catch((error) => setIsError(error))
.finally(() => setIsLoading(false));
}, []);
return (
<View>
{places.map(({ name, distance }) => (
<View>
<Text>name</Text>
<Text>{name}</Text>
<Text>{distance}</Text>
</View>
))}
</View>
);
};
export default App;
2
Answers
you are not updating the state here, only consoling the data,
I’ve haven’t worked with React Native but if it’s the same as regular React, then the first problem I see is that each element inside your map should have a key:
You also need to handle the loading state. Because when App first runs, places is undefined, so you are calling
undefined.map
which will probably throw an error. An early return would suffice.And I also don’t see the
setPlaces()
being called, I assume you replaced it with the console log?