0

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())
          )
        )
      );
  };
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Did you checked if you have a object data response in your fetch? In "res.json()". Use console.log(res.json()) to check if your call was correctly. – Wiharlley Yitzhak Aug 18 '22 at 15:13
  • i was able to display the restaurant data from yelp before i added the filter method, so i'm being so confused about it – lawrencelu0904 Aug 18 '22 at 15:37
  • see your response .then(json) => consol.e.log(json)). I think you don't have "businesses" in your response. you need to check the sent response structure. – Wiharlley Yitzhak Aug 18 '22 at 15:41
  • sorry for the editing it's too long so I separated into three pieces – lawrencelu0904 Aug 18 '22 at 16:04
  • Editing is not adding information in comments. Please [move](https://stackoverflow.com/posts/73405317/edit) the appropriate information to the question. You can [edit](https://stackoverflow.com/posts/73405317/edit) ([change](https://stackoverflow.com/posts/73405317/edit)) the question. (But ***without*** "Edit:", "Update:", or similar - the question should appear as if it was written today.) Thanks in advance. – Peter Mortensen Aug 20 '22 at 14:54
  • When I said "***without*** "Edit:", "Update:", or similar - the question should appear as if it was written today", I meant it. – Peter Mortensen Aug 20 '22 at 14:57
  • Please review *[Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/)* (e.g., *"Images should only be used to illustrate problems that* ***can't be made clear in any other way,*** *such as to provide screenshots of a user interface."*) and [do the right thing](https://stackoverflow.com/posts/73405317/edit). Thanks in advance. – Peter Mortensen Aug 20 '22 at 15:01

2 Answers2

0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Asad raza
  • 71
  • 3
  • what is the repsonse of the api call ? have u console.log it ? – Asad raza Aug 18 '22 at 15:24
  • sorry the "filter" typo was my fault, I changed it into filter but still got the same error. and since before i added the line: .filer((business) => business.transactions.includes(activeTab.toLowerCase()) ) ) my screen actually display the data what i want, so i'm not sure what went wrong on either the filter() or the transactions – lawrencelu0904 Aug 18 '22 at 15:34
  • Follow-up questions belong in comments to [the question](https://stackoverflow.com/questions/73405317/), not in your answer. *Stack Overflow* [is not a forum](https://meta.stackexchange.com/a/92115). Can you [move](https://stackoverflow.com/posts/73405569/edit) them there, please? Thanks in advance. – Peter Mortensen Aug 20 '22 at 14:49
0

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.
        });
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131