skip to Main Content

I’m new to React Native. I was building my school project and tried to fetch the data to my components, but instead I got this error. I’ve searched for this error on Google, but I did not get that much information.

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())
          )
        )
      );
  };

2

Answers


  1. In the last function where you are filtering using

    json.businesses.filer
    

    This a typo. It’s filter instead of filer.

    Other than 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 it’s undefined at any point, JavaScript can’t perform a map on it, hence the error.

    Login or Signup to reply.
  2. 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.
            });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search