I was trying to replicate a personal project to set a Spinner loader while the data fetch is being load but I got another error before.
I was reading in other questions like this one, that in order to avoid a useEffect()
infinite loop I have to add an empty array to the end, but still it doesn't work.
This is my code, it just re-renders infinitely despite the empty array added.
src/components/Users.js
import React, { useState, useEffect, useContext } from "react";
import GlobalContext from "../context/Global/context";
export default () => {
const context = useContext(GlobalContext);
const [users, setUsers] = useState([]);
async function getUsers() {
context.setLoading(true);
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (response.ok) {
context.setLoading(false);
const data = await response.json();
setUsers(data);
} else {
console.error('Fetch error');
}
}
useEffect(() => {
getUsers();
}, []);
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
};
This is the non-working Sandbox, I am not sure why this is happening, any comments are appreciated.