Home > Back-end >  Undefined error while trying to map over array of objects React Native
Undefined error while trying to map over array of objects React Native

Time:03-03

I've been trying to map an array of items which is passed from my Home Component to another but I'm always getting the error restaurants.map is Undefined. I fetch the data from Yelp and store it in a State(Home Component), then I pass this to another component, retrieve it through props and try to map through it(RestaurantItems Component). Please help. I have attached the code of my two components..

Home Component

import { View, Text, StatusBar, ScrollView } from "react-native";
import React, { useEffect, useState } from "react";
import HeaderTabs from "../components/HeaderTabs";
import SearchBar from "../components/SearchBar";
import Categories from "../components/Categories";
import RestaurantItems from "../components/RestaurantItems";

const YELP_API_KEY =
  "6NE-noDkyFUDKVVo2B8POXtwsAIBEe7QTnZEwMpvNE-5asFQ1q0_jh7iJ5KqprLD3sVt2htFrZbe4V2rHbdXgUcqkMSquQADGcGOTh_ANZ1DRT_tnFKZBHT4Hh0eYn";

export default function Home() {
  const [restaurantData, setRestaurantData] = useState();

  const getRestaurantFromYelp = async () => {
    const response = await fetch(
      `https://api.yelp.com/v3/businesses/search?term=restaurants&location=san francisco`,
      {
        method: "GET",
        headers: {
          Authorization: `Bearer ${YELP_API_KEY}`,
        },
      }
    );

    const data = await response.json();
    setRestaurantData(data);
  };

  useEffect(() => {
    getRestaurantFromYelp();
  }, []);

  return (
    <View style={{ backgroundColor: "#eee", flex: 1 }}>
      <StatusBar barStyle="dark-content" backgroundColor="#eee" />
      <View style={{ backgroundColor: "#fff", padding: 15 }}>
        <HeaderTabs />
        <SearchBar />
      </View>
      <ScrollView showsVerticalScrollIndicator={false}>
        <Categories />
        <RestaurantItems restaurants={restaurantData} />
      </ScrollView>
    </View>
  );
}

RestaurantItems Component

import React from "react";

import { MaterialCommunityIcons } from "react-native-vector-icons";

export default function RestaurantItems({ restaurants }) {
  console.log(restaurants);

  return (
    <View>
      {restaurants.map((single_data) => (
        <Text>{single_data.name}</Text>
      ))}
    </View>
  );
}


CodePudding user response:

This has been asked so many times! Your state is not initialized, so at first render, when your datas are not loaded yet, you have an error. So initiliaze your state with an empty array

const [restaurantData, setRestaurantData] = useState([]);
  • Related