Reputation: 111
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
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