Home > Blockchain >  Undefined is not an Object? (filter data from api's)
Undefined is not an Object? (filter data from api's)

Time:08-19

I'm actually new in react-native. I was building my school project and try to fetch the data to my components, but instead I got this error, I've search for this error on google but not that many info, I have totally no idea about this, and been stuck in here for a long time! error 1

export default function Home() {
  const [recipeData, setRecipeData] = React.useState([localRestaurants]);
  const [city, setCity] = useState("Taipei");
  const [activeTab, setActiveTab] = useState('Delivery');

  const getRecipeFromYelp = () => {
    const yelpUrl =
      `https://api.yelp.com/v3/businesses/search?term=restaurants&location=${city}`;

  const apiOptions = {
    headers: {
      Authorization: `Bearer ${YELP_API_KEY}`,
    },
  };

    return fetch(yelpUrl, apiOptions)
      .then((res) => res.json())
      .then((json) => 
        setRecipeData(json.businesses));
  };

  useEffect(() => {
    getRecipeFromYelp();
  }, [city, activeTab]);

  return (
    <SafeAreaView style={{
        backgroundColor: "#eee",
        flex: 1,
    }}>
        <View style={{
            backgroundColor: 'white',
            padding: 15,
        }}>
            <HeaderTabs activeTab={activeTab} setActiveTab={setActiveTab}/>
            <SearchBar cityHandler={setCity} />
        </View>
        <ScrollView showsVerticalScrollIndicator={false}>
          <Categories />
          <RecipeItems recipeData={recipeData} />
        </ScrollView>
        <Divider width={1} />
        <BottomTabs />
    </SafeAreaView>
  );
}

here's my Home screen

export default function RecipeItems(props) {
  return (
    <TouchableOpacity activeOpacity={1} style={{
        marginBottom: 30,
    }}>
        {props.recipeData.map((recipe, index) => (
            <View
                key={index} 
                style={{
                marginTop: 10,
                padding: 15,
                backgroundColor: "white",
            }}>
                <RecipeImage image={recipe.image_url}/> 
                <RecipeInfo 
                    name={recipe.name} 
                    rating={recipe.rating}
                />
            </View>
        ))}
    </TouchableOpacity>
  );
}

const RecipeImage = (props) => (
    <>
    <Image
        source={{
            uri: props.image,
        }}
        style={{
            width: "100%",
            height: 180,
        }}
    />
    <TouchableOpacity style={{
        position: 'absolute',
        right: 20,
        top: 20,
    }}>
        <MaterialCommunityIcon name='heart-outline' size={25} color='#fff'/>
    </TouchableOpacity>
    </>
);

const RecipeInfo = (props) => (
    <View style={{
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
        marginTop: 10,
    }}>
        <View>
            <Text style={{
                fontSize: 15,
                fontWeight: 'bold',
            }}>{props.name}</Text>
            <Text style={{
                fontSize: 13,
                color: "gray",
            }}>30-45 • min</Text>
        </View>
        <View style={{
            backgroundColor: "#eee",
            height: 30,
            width: 30,
            alignItems: 'center',
            justifyContent: 'center',
            borderRadius: 15,
        }}>
            <Text>{props.rating}</Text>
        </View>
    </View>
)

and my component

And since I skipped this error I added some new code to filter the api's data and also got this error too

error 2

    return fetch(yelpUrl, apiOptions)
      .then((res) => res.json())
      .then((json) => 
        setRecipeData(json.businesses.filer((business) => 
          business.transactions.includes(activeTab.toLowerCase())
          )
        )
      );
  };

I really need some help, Big Thanks!

CodePudding user response:

In the last function where you are filtering using

json.businesses.filer

This a typo its filter instead of filer .

Other then that can you confirm that you are getting an array in response of the api call ?

I would like to know what is the initial value of the recipeData ?

If its undefined at any point Js cant perform map on it hence the error .

CodePudding user response:

You need to DEBUG your steps until you find the error. Whether checking the output of owning the object you are accessing or otherwise.

I advise you to use catch to avoid crashing the application until you find the error. It's certainly filtering an object that doesn't exist in the fetch return.

Add "await" to your fetch and "async" in the top of function.

return await fetch(yelpUrl, apiOptions)
        .then((res) => res.json())
        .then((json) => {
            //Try DEBUG your code to check where are the error in filter...
            console.log(json);
            console.log(json.businesses.filer((business) => business.transactions.includes(activeTab.toLowerCase())));
            return null // or other return to don't crash your app.
        }

        ).catch((error) => {
            console.log('Error catch', error);
            return null // or other return to don't crash your app.
        });

  • Related