简体   繁体   中英

Unmounted component - React Native

I have to functions/const to get data from API:

    const [isLoadingRoom, setLoadingRoom] = useState(true);
    const [isLoadingLobby, setLoadingLobby] = useState(true);
    const [rooms, setRooms] = useState([]);
    const [lobbies, setLobbies] = useState([]);

    const getRooms = async () => {
      let isMounted = true;

      async function fetchData() {
        const response = await fetch('https://yatzy.live/functions/api/getRooms.php');
        const json = await response.json();
  
        // 👇️ only update state if component is mounted
        if (isMounted) {
          setRooms(json);
          setLoadingRoom(false);
        }
      }
  
      fetchData();

     return () => {
      isMounted = false;
     }
   }

   const getLobbies = async () => {
      let isMounted = true;

      async function fetchData() {
        const response = await fetch('https://yatzy.live/functions/api/getLobbies.php');
        const json = await response.json();
  
        // 👇️ only update state if component is mounted
        if (isMounted) {
          setLobbies(json);
          setLoadingLobby(false);
        }
      }
  
      fetchData();

     return () => {
      isMounted = false;
     }
 }

    useEffect(() => {
      const roomInterval = setInterval(() => {
        getRooms();
        getLobbies();
      }, 5000);
      return () => clearInterval(roomInterval);
    }, []);

The API gets data every 5 second, but after a while I get this message:

Warning: 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.

I have tried different approaches to fetch the API with const, functions, async etc. but I get this error message anyway.. Any tips?

useRef rather than normal variable:

const isMountedRef = useRef(true);

    useEffect(() => {
      const roomInterval = setInterval(() => {
        getRooms();
        getLobbies();
      }, 5000);
      return () => {
    clearInterval(roomInterval);
    isMountedRef.current = false;
};
    }, []);

and change check conditions to

if(isMountedRef.current){
// execute setState
}

Hope it helps. feel free for doubts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM