Reputation: 177
I was trying to display data from a fetch function to my render app in react native.
I was able to get the data from my fetch but i am not able to display it on the app..
this is my code:
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
const fetchDatos = async () => {
return fetch('http://localhost:8000/api/consulta').then(response => {
return response.json();
})
.then(responseJson => {
var Nombre = responseJson.Participante.InfoParticipante['@attributes'].Nombre;
});
}
return (
<View>
<Button
title='press me'
onPress={fetchDatos}
/>
<Text>{Nombre}</Text>
</View>
);
}
As you can see in the code above I get the data stored in the var ''Nombre'' and I am trying the display it in the app but it's telling me Uncaught ReferenceError: Nombre is not defined
Does anyone know how to fix this, I would appreciate it a lot!
Upvotes: 1
Views: 208
Reputation: 1001
This will work
import React,{useState} from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
const [nombre,setNombre]=useState()
const fetchDatos = () => {
return fetch('http://localhost:8000/api/consulta').then(response => {
return response.json();
})
.then(responseJson => {
setNombre(responseJson.Participante.InfoParticipante['@attributes'].Nombre);
});
}
return (
<View>
<Button
title='press me'
onPress={fetchDatos}
/>
<Text>{nombre}</Text>
</View>
);
}
Upvotes: 1