Am actively creating a react native app for my college studies ! In that am using external api as data source. The problem am facing is that sometimes am getting data in single object and sometimes its in array format. How to handle this in react native perspective ?
As am maping jsx considering it as array but when i get object it throws error
My data example:
const data = { // this is example of single object
entry: {
key: "0",
value: "Patrik"
}
}
const data = { // this is example of array
entry: [
{
key: "0",
value: "Patrik"
},
{
key: "1",
value: "John"
}],
}
So this is how i get data from external api, and now my react native jsx code:
{ data.entry.map(o => {
<View key={o.key}>
<View style={{ paddingLeft: 25 }}>
<Text style={{ fontWeight: 'bold' }}>{o.value}</Text>
</View>
</View>
})
}
So, when i get array, it works but when i get object this throws error ! Any help on this ?
To render an array of objects in react with JSX we need to use Array. map() to transform the object into something react can make use of because you cannot directly render an object into React. Instead, by using Array.
To create and use an array in react native, just use square brackets [] it will create an array like the below example.
You should do Array.isArray(data.entry)
to check if you have an array of object or a single object. And perform the logic based on that.
Convert Object to Array so you won't get error.
if(!Array.isArray(data.entry)){
data = { entry: [data.entry] };
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With