skip to Main Content

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;

data from api

2

Answers


  1. you are not updating the state here, only consoling the data,

          useEffect(() => {
        axios
          .post(
            "https://where2playdk.herokuapp.com/nearest?lat=55.70232019168349&lon=12.561693791177802"
          )
          .then((response) => setPlaces(response.data)) // here is the 
                                                         //mistake
          .catch((error) => setIsError(error))
          .finally(() => setIsLoading(false));
      }, []);
    
    Login or Signup to reply.
  2. 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:

    {places.map(({ name, distance }) => (
          <View key={name}>
            {/* ... */}
          </View>
          ))} 
    

    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.

    if (!places) return <Text>Loading...</Text>
    

    And I also don’t see the setPlaces() being called, I assume you replaced it with the console log?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search