skip to Main Content

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.

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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[0]?.newOne?.b}</Text>
          <Text>{data?.data?.items[0]?.newOne?.c}</Text>
       </View>
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search