Aymen Aymen
Aymen Aymen

Reputation: 281

Display nested Json array fetched data React native

So i'm new to react native and i'm trying to display nested elements of a Json fetched data, but i can't figure out how to do it. After using react hooks in the fetch api:

export default function MedProfilScreen({ route }) {
  //const {id,name,specialite,work}=route.params;
  const [data, setData] = useState([]);
  useEffect(() => {
    fetch("http:......")
      .then(response => response.json())
      .then(res => {
        setData(
          res);
        console.log(res);
      })
      .done();
  },[]);
}

i got this reponse:

Array [
  Object {
    "code": "12459552",
    "id": 7,
    "name": "Dr xavier vilan",
    "speciality": "Cardio",
  },
  Object {
    "education": Array [
      Object {
        "date_debut": "2020-02-07",
        "date_end": "2020-02-06",
        "diploma": "asmaa",
        "school": "asmaa",
        "city": "vullez",
      },
      ]}
]

so i want to display for example: name: Dr xavier.. diploma: asmaa

return(
<View>  name: Dr xavier.. diploma: asmaa            </View>
)

anyone have an idea how to do it please.thank you

Upvotes: 1

Views: 1343

Answers (4)

joy08
joy08

Reputation: 9662

Try this referring to the items that you want

return(
     <View>  
          <Text> name: {data[0].name} diploma: {data[1].education[0].diploma}         
           </Text>
     </View>
)

Upvotes: 0

Tim
Tim

Reputation: 10719

I don't know it this is what you are looking for, but I'll give it a try:

Code:

const renderText = () => {
    // as soon as we received the data, we will display it
    if (data.length > 0){
      return (
         <Text> name: {data[0].name} diploma: {data[1].education[0].diploma}</Text>
      )
    }
}
return (
  <View>
     {renderText()}
  </View>
);

Output:

output

Demo:

https://snack.expo.io/rkbsDdoU8

Upvotes: 1

SDushan
SDushan

Reputation: 4641

Since you already saved your response inside data your data should like this,

data = [
  {
    code: "12459552",
    id: 7,
    name: "Dr xavier vilan",
    speciality: "Cardio"
  },
  {
    education: [
      {
        date_debut: "2020-02-07",
        date_end: "2020-02-06",
        diploma: "asmaa",
        school: "asmaa",
        city: "vullez"
      }
    ]
  }
]

Now you can access name & diploma as below,

name: data[0].name
diploma: data[1].education[0].diploma

Hope this helps you. Feel free for doubts

Upvotes: 1

Uladzislau Ulasenka
Uladzislau Ulasenka

Reputation: 582

try this:

return (
   <View>{JSON.stringify(data, null, 2)}</View>
)

Upvotes: 0

Related Questions