'Having a problem using useEffect to fetch data in react native since changing from a class to function
I am having a problem using the useEffect method to fetch data on load and then to watch for changes in a state.
I am not sure if it loading the data at all or I am using the fetch correctly as I am simply trying to alert the data which I know it will not do correctly because it is an array but it basically does not even call the alert but the code worked in class, this is a functional component.
Any ideas where I am going wrong? Thanks and the code is below and I am not asking anyone to do this, just point me out where I am going wrong as I am very to RN:
import React, { useState, useEffect, Component } from 'react';
import { ScrollView, StyleSheet, Button, View, Text } from 'react-native';
import { List, ListItem } from 'react-native-elements';
export default function App() {
const [users, setUsers] = useState([]);
const loadusers = async () =>{
try{
let data = await fetch("https://randomuser.me/api/?results=20&nat=us", {method: 'GET'});
let json = await data.json();
setUsers(json);
}
catch(err){
console.log("Im catching the error");
console.log(err);
setUsers([]);
}
}
useEffect(() => {
loadusers();
},[])
useEffect(() => {
//alert(users)
},[users])
return (
<ScrollView style={styles.container}>
<List>
{users.map((user, i) => (
<ListItem
roundAvatar
avatar={{ uri: user.picture.thumbnail }}
key={i}
title={user.name.first + " " + user.name.last}
/>
))}
</List>
</ScrollView>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 50,
backgroundColor: '#ecf0f1',
},
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
