Trldonik
Trldonik

Reputation: 111

How to access results from API to display to my UI? (React Native)

I'm currently making an API call inside my App component in React Native. I'm using fetch to capture a few values and storing them in variables within my fetch. How can I access those varaiables inside my return statement to display to my UI?

This is what my component looks like right now, I need "lessonDesc" and "lessonName" values inside my return statement where you see "NEED DATA HERE"

export default function App() {



fetch(contentURL).then((response) => response.json()).then((json) => {
  let lessonName = json.fields.lessonName
  console.log(json.fields.lessonName);
  let lessonDesc = json.fields.lessonDesc

  console.log(json.fields.lessonDesc);
  return lessonDesc
}).catch((error) => {
  console.error(error);
})


return (
  
    <View style={styles.container}>
      <Text>{NEED DATA HERE}</Text>
      <StatusBar style="auto" />
    </View>
  );
}```

Upvotes: 0

Views: 381

Answers (1)

MHP
MHP

Reputation: 663

Best way that is you use useState for updating variables and you can access that variables in all around in the your Component , also you are be able to define states separately or all together , in this case we defined separately. So you can try it:

export default function App() {
   const [lessonName, setLessonName] = React.useState("");
   const [lessonDesc, setLessonDesc] = React.useState("");

   React.useEffect(()=>{
    fetch(contentURL).then((response) => 
      response.json()).then((json) => {
        setLessonName(
          json.fields.lessonName
        );
        setLessonDesc(
           json.fields.lessonDesc
        );
      }).catch((error) => {
        console.error(error);
      })
   } , []);

return (
  
    <View style={styles.container}>
      <Text>{NEED DATA HERE}</Text>
      <StatusBar style="auto" />
    </View>
  );
}

Upvotes: 1

Related Questions