I'm trying to fetch data from a nested array from an API in react native.
so my coding is like this
export default const App= () =>{
const [data, setData] = useState([]);
console.log(data);
//Some fetch code here
//setData happen here
return (
<View >
<Text >fetched data</Text>
<Text>{data?.data?.items?.newOne?.a}</Text>
<Text>{data?.data?.items?.newOne?.b}</Text>
<Text>{data?.data?.items?.newOne?.c}</Text>
</View>
)
};
and the supposed array is like this
arr = { code: 1, data:{ items:[{newOne:{a:2, b:4, c:6}, id:00},], totality: 1}}
can someone tell me what I'm doing it wrong here? I'm new to js and also react native. I received blank whenever I run this code.
CodePudding user response:
items
is an array, so you have to access it as one
return (
<View >
<Text >fetched data</Text>
<Text>{data?.data?.items[0]?.newOne?.a}</Text>
<Text>{data?.data?.items[1]?.newOne?.b}</Text>
<Text>{data?.data?.items[2]?.newOne?.c}</Text>
</View>
)
CodePudding user response:
You can try something like this :
export default const App= () =>{
const [data, setData] = useState([]);
console.log(data);
//Some fetch code here
//setData happen here
const itemsObject = data?.data?.items[0] ?? {}
return (
<View >
<Text >fetched data</Text>
<Text>{itemsObject?.newOne?.a}</Text>
<Text>{itemsObject?.newOne?.b}</Text>
<Text>{itemsObject?.newOne?.c}</Text>
</View>
)
};
Hope it helps