How to set local array to global react?

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.

Answer

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

Leave a Reply

Your email address will not be published. Required fields are marked *