Search code examples
reactjsstateuse-effect

React useEffect Infinite loop when fetching from api


I'm trying to store the data from my fetch request into a state, but it ends up infinitely looping even when there's no dependency. When I remove the code inside the div where I filter out and map out the array it seems to not infinitely loop but I have no clue as to why filtering/mapping would cause it to loop like that

function App() {
  const [searchTerm, setSearchTerm] = useState("");
  const [students, setStudents] = useState([]);
  const [isActive, setIsActive] = useState(false);
  const average = (array) => {
    return array.reduce((a, b) => a + parseFloat(b), 0) / array.length;
  };
  useEffect(() => {
    const api = async () => {
      await fetch("https://api.hatchways.io/assessment/students")
        .then((res) => res.json())
        .then((data) => setStudents(data.students));
    };

    api();
  }, []);
  return (
    <div className='bg-gray-300 h-screen flex items-center justify-center'>
      {students
        .filter((student) => {
          if (searchTerm === "") {
            return student;
          } else if (
            student.firstName
              .toLowerCase()
              .includes(searchTerm.toLowerCase()) ||
            student.lastName.toLowerCase().includes(searchTerm.toLowerCase())
          ) {
            return student;
          }
        })
        .map((student, i) => (
          <div
            key={i}
            className='flex items-center space-x-8 px-8 py-3 border-b'>
            <div className='flex items-start w-full space-x-7'>
              <div className='border overflow-hidden rounded-full'>
                <img
                  className='w-24 h-24 bg-contain'
                  src={student?.pic}
                  alt='student school portrait'
                />
              </div>
              <div className='flex flex-col justify-between space-y-4 w-full'>
                <div className='flex items-center justify-between'>
                  <h1 className='font-bold text-5xl'>
                    {student?.firstName} {student?.lastName}
                  </h1>
                  <button onClick={setIsActive(!isActive)}>
                    {isActive ? (
                      <AiOutlinePlus className='h-7 w-7' />
                    ) : (
                      <AiOutlineMinus className='h-7 w-7' />
                    )}
                  </button>
                </div>
                <div className='pl-3'>
                  <p>Email: {student?.email}</p>
                  <p>Company: {student?.company}</p>
                  <p>Skill: {student?.skill}</p>
                  <p>Average: {average(student?.grades).toFixed(2)}%</p>
                </div>
              </div>
            </div>
          </div>
        ))}
    </div>
  );
}

Solution

  • If you use async/await you don't need to chain .then() . Try updating your useEffect as :

         useEffect(() => {
            api();
          }, []);
    
            const api = async () => {
                 let res = await fetch("https://api.hatchways.io/assessment/students");
                 let data = await res.json();
                 setStudents(data.students)
            }; 
    

    Also, Use arrow function in the button click handler as:

    <button onClick={()=>setIsActive(!isActive)}>