Home > Enterprise >  Can't setState inside useEffect with "useIsFocused()" from react-navigation as depend
Can't setState inside useEffect with "useIsFocused()" from react-navigation as depend

Time:06-03

I use the useIsFocused() function from react-navigation/native as a dependency of useEffect to listen to screen focus, so when I navigate back it enters the if with the isFocused and the myRoute.params.isChecked to execute the function.

But it's not updating the route state on setRoute(newRoute); and setIsLoading(false). The setIsLoading(true) inside the function is called but the one inside the useEffect route isn't because it never call the route update. The screen keeps loading infinitely because of that.

Why it not updates the isLoading and route states?

import React, { useEffect, useState } from 'react';
import { useFocusEffect, useIsFocused } from '@react-navigation/native';

const MyRoute = ({ navigation, route: myRoute }) => {
  const [route, setRoute] = useState({});
  const [isLoading, setIsLoading] = useState(true);

  const isFocused = useIsFocused();

  /** ... */ 

  useEffect(() => {
    console.log('route call')
    if (Object.keys(route).length) {
      setIsLoading(false);
    }
  }, [route]);

  useEffect(() => {
    console.log(isLoading);
  }, [isLoading]);

  useEffect(() => {
    // trigger route refresh on navigate when checkin/checkout
    if (isFocused && myRoute.params?.isChecked) {
      const updateRouteWithCheckInOut = () => {
        setIsLoading(true);
        const newRoute = route;

        for (let i = 0; i < newRoute.visitas.length; i  ) {
          const { sub_id, check_in_out } = myRoute.params;

          if (newRoute.visitas[i].sub_id === sub_id) {
            newRoute.visitas[i].realizada = true;
            newRoute.visitas[i].check_in_out = check_in_out;
          }
        }
        debugger;

        setRoute(newRoute);
      };

      updateRouteWithCheckInOut();
    }
  }, [isFocused]);

  /** ... */
}

CodePudding user response:

you are updating some properties of visitas array in your for loop. the thing is you are just mutating some propery and update your route with the same object. if you check route === newRoute after the for loop you see that it evaluates to true. because they are the same object. and when you update your route with the same object react doesn't rerender your component. you should update your route like this:

setRoute(...newRoute)
  • Related