-2

I have an array of Names(Commented in code):=

export default Main_homepage = (props) => {
 var Names = []

       useEffect(() => {
            fetch('https://www.amrutras.com/Items.php')
                .then((response) => response.json())
                .then((responseJson) => {
                    {
                        Names = responseJson //***Names Array***
                        console.log(Names[0].ID) //****Its working, I am getting outpu for this in console
                        console.log(Names[0].Name)
                    }   
                })
                .catch((error) => {
                    console.error(error)
                })
        })
return(
     <View>{console.log(Names[0].ID)}</View>  //****Its not working.
)
}

But when I am trying to access outside of the use effect it's not working.

In short, I am trying to access the response array in JSX.

sanket kheni
  • 1,482
  • 2
  • 12
  • 29

2 Answers2

1

So this is an asynchronous call and it will not work because after the return statement is sent out, the value gets changed.

Change Names into a state hook - Using the State Hook:

// Remove this
// var Names = []
// Replace with:
const [Names, setNames] = useState([]);

And when you're updating, use setNames:

// Remove this inside the promise
// Names = responseJson
// Replace with the following:
setNames(Names);

If you want to understand what an asynchronous call, read more at How do I return the response from an asynchronous call?

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

As suggested by Praveen Kumar sir, utilize useState hook.

Here is the Full Working Example: Expo Snack

enter image description here

import React, { useEffect, useState } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

export default App = (props) => {
  const [names, setNames] = useState([]);

  useEffect(() => {
    fetch('https://www.amrutras.com/Items.php')
      .then((response) => response.json())
      .then((responseJson) => {
        {
          console.log(responseJson);
          setNames(responseJson); //***Names Array***
        }
      })
      .catch((error) => {
        console.error(error);
      });
  }, []);
  return (
    <View style={{ marginTop: Constants.statusBarHeight }}>
      <Text>{JSON.stringify(names)}</Text>
    </View>
  );
};

Ketan Ramteke
  • 10,183
  • 2
  • 21
  • 41