1

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!

5
  • are you using hooks or class components? Commented Mar 13, 2020 at 20:10
  • Nombre is out of scope for one.. Commented Mar 13, 2020 at 20:11
  • scope of var Nombre is within the fetchDatos funciton. you need to use state variable for that Commented Mar 13, 2020 at 20:11
  • Use this - robinwieruch.de/react-hooks-fetch-data - the answers below don't really cover all cases so you will most likely run into issues. Commented Mar 13, 2020 at 20:23
  • Alright @goto1 I will read the guide thanks! Commented Mar 13, 2020 at 20:33

1 Answer 1

1

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>
  );

}
Sign up to request clarification or add additional context in comments.

2 Comments

GREAT! this worked @Prakash Reddy Potlapadu :D, just needed to fix this line: const [nombre,setNombre]= React.useState('');
@BetolGM I imported useState in the first line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.