I want to load the list of all users from an endpoint on the first load of the app.
But, I am getting the Too many re-renders. React limits the number of renders to prevent an infinite loop.
error while running this code.
It was working expected with a json object but I replace json with endpoint then I start getting this.
My code is:-
export default function App() {
const [profiles, setProfiles] = useState()
const [loader, setLoader] = useState()
setLoader(false)
const getProfiles = async () => {
console.log('start')
const res = await fetch("https://reqres.in/api/users?page=1")
const result = await res.json()
if(result != 'undefined') {
setProfiles(result.data)
setLoader(true)
}
}
useEffect(() => {
getProfiles();
}, []);
return (
<View style={styles.container}>
<ScrollView
contentContainerStyle={{
flexGrow: 1
}}
keyboardShouldPersistTaps='handled'
>
<View style={styles.tasksWrapper}>
<Text style={styles.sectionTitle}>Users List</Text>
<View style={styles.items}>
{
loader &&
profiles.map((profile, index) => {
setLoader(false)
return (
<TouchableOpacity key={index} onPress={() => completeTask(index)}>
<UserList profile={profile} />
</TouchableOpacity>
)
})
}
</View>
</View>
</ScrollView>
</View>
);
}
2
Answers
You made a mistake
remove this and use like
And your function should be
Hey you should never call setSTate inside render methods:
Try this code :
ive removed all set state methods from render. here is a working example Expo link
Hope it helps. feel free for doubts