Search code examples
reactjsmemory-leaksstateuse-effect

UseEffect can't performe state update


I am getting this UseEffct error that causes my window to render an empty page error ="Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."

my Component Code

import React, { useEffect, useState } from "react";
import { instance } from "../Data/axios";

const Row = ({ title, fetchURL }) => {
  const [movies, setMovies] = useState([]);
  //  A snippet of code that runs on a certain condition
  useEffect(() => {
    async function fetchData() {
      const data = await instance.get(fetchURL);
      setMovies(data.data.results);
    }
    fetchData();
  }, [fetchURL]);

  const base_url = "https://image.tmdb.org/t/p/original/";

  console.log(movies);
  return (
    <div className="rows">
      <h3>{title}</h3>
      <div className="rows_poster">
        {movies.map((movie) => {
          <div key={movie.id}>
            <img src={`${base_url}${movie.poster_path}`} />
          </div>;
        })}
      </div>
    </div>
  );
};

export default Row;

Solution

  • This has worked for me:

    useEffect(() => {
      let mounted = true;
      async function fetchData(){
        const data = await instance.get(fetchURL);
        if (mounted) {
          setMovies(data.data.results);
        }
      };
      fetchData();
      return ()=> {mounted = false}
    }, []);