Home > Enterprise >  React useEffect Infinite loop when fetching from api
React useEffect Infinite loop when fetching from api

Time:12-07

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

CodePudding user response:

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

CodePudding user response:

mostly I try to call function inside useEffect while code to that fucntion outside of useEffect. it works for me try that.

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

CodePudding user response:

Try with async-await syntax

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(
        "https://api.hatchways.io/assessment/students"
      );
      const result = await response.json();

      console.log("res", result);
    };

    fetchData();
  }, []);

In case if you want to handle errors, you need to add try catch block.

CodePudding user response:

The issue was not setting the arrow function on the onclick of the button: <button onClick={() => setIsActive(!isActive)}>

CodePudding user response:

<button onClick={setIsActive(!isActive)}> This may be the culprit. You're changing the state in every rander. You should instead pass () => setIsActive(!isActive) as onClick handler.

  • Related