I'm making an app with React Native where I display F1 cars as a school project and I get my data(titles, images,..) from posts on my Wordpress website. I'm doing this using fetch. (Note: I'm very new to this so I'm sorry if my wording is a bit complicated.)
I!m using postman to find my data and I found my image that I want to use:
"og_image": [
{
"width": 1920,
"height": 1080,
"url": "https://tibomertens.be/wp-content/uploads/2022/12/F1-75_JPG_SPONSOR_00004.jpg",
"type": "image/jpeg"
}
],
So in my React Native code I wrote this to get the image url:
{item.id === 572 && (
<Image
style={{ width: 50, height: 200 }}
source={{ uri: `${item.og_image[0].url}` }}
/>
)}
But it gives an error "[TypeError: undefined is not an object (evaluating 'item.og_image[2]')]".
full code:
const Cars = ({ navigation }) => {
const [Cars, setCars] = useState([]);
const getCars = async () => {
try {
const response = await fetch(
"https://tibomertens.be/wp-json/wp/v2/posts?categories=8",
{}
);
const json = await response.json();
setCars(json);
console.log(Cars);
console.log("hey");
} catch (error) {
console.error(error);
}
};
useEffect(() => {
getCars();
}, []);
return (
<View>
<FlatList
data={Cars}
renderItem={({ item }) => (
<View>
<Text>
{"\n"}
{item.id === 572 && (
<Image
style={{ width: 50, height: 200 }}
source={{ uri: `${item.og_image[0].url}` }}
/>
)}
<Text>
{item.title.rendered} {"\n"}{" "}
</Text>
<Text>{item.rttpg_excerpt}</Text>
</Text>
<Pressable
onPress={() =>
navigation.navigate("Details", {
itemTile: item.title.rendered,
})
}
>
<Text>bekijk product</Text>
</Pressable>
</View>
)}
></FlatList>
</View>
);
};
Thanks for reading and hopefully someone can help me!
CodePudding user response:
updated answer. Change this code:
{item.id === 572 && (
<Image
style={{ width: 50, height: 200 }}
source={{ uri: `${item.og_image[0].url}` }}
/>
)}
to:
{item.yoast_head_json?.og_image !== undefined && <Image
style={{ width: 50, height: 200 }}
source={{ uri: `${item.yoast_head_json.og_image[0].url}` }}
/>
}