Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
why does useCallback return an empty array

in react native app,

i'm trying to get data from async function which will bring me back Promise<AlarmType[] | undefined>

Q1. so, in getAlarms.then() function, the undefined case is filtered and an empty array is printed in my console.

and after saving code in vscode, the console prints an array with proper data

Q2.the reason why i use useLayoutEffect and useEffect separately is i just wanna separate the data fetching code from the react navigation header setOption code but i'm not sure if it is a good practice

Is there any better ways to do this? edit: i’m using react-native-simple-alarm

  const [alarms, setAlarms] = useState<AlarmType[]>([]);

  const fetchData = useCallback(() => {
    getAlarms().then(response => {
      if (response) setAlarms(response);
      else console.log('undefined | empty array returned');
    });
  }, []);

  useLayoutEffect(() => {
    fetchData();
    const willFocusSubscription = navigation.addListener('focus', () => {
      fetchData();
    });
      console.log(alarms) // here, this function is called twice, and return empty array
    return willFocusSubscription;
  }, []);

  useEffect(() => {
    navigation.setOptions({
      headerLeft: () => <Icon name="trash-can-outline" size={30} 
          onPress={() => {
            deleteAllAlarms();
            fetchData();
          }}/>,
      headerTitle: 'Alarm',
      headerRight: () =><Icon name="plus" size={30} onPress={() => navigation.navigate('ModalStackView')}/>,
    });
  }, []);

in getAlarms.ts

export const getAlarms = async () => {
  try {
    return await RNGetAlarms();
  } catch (error) {
    console.log('setting call error' + error);
  }
};
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The useLayoutEffect is called before the render cycle of React which means before rendering the JSX content in your code this hook is being called.

So, If there is any requirement before JSX render like change header name, show header left or right buttons, etc.

and the useEffect is called after the initial render cycle is completed. when the JSX code is done with the rendering UI part.

So, I think your code should look like below:

const [alarms, setAlarms] = useState<AlarmType[]>([]);

const fetchData = useCallback(() => {
    getAlarms().then(response => {
        if (response) setAlarms(response);
        else console.log('undefined | empty array returned');
    });
}, []);

useEffect(() => {
    const willFocusSubscription = navigation.addListener('focus', () => {
        fetchData();
    });
    return willFocusSubscription;
}, [fetchData, navigation]);

useLayoutEffect(() => {
    navigation.setOptions({
        headerLeft: () => <Icon name="trash-can-outline" size={30} 
            onPress={() => {
                deleteAllAlarms();
                fetchData();
            }}/>,
        headerTitle: 'Alarm',
        headerRight: () =><Icon name="plus" size={30} onPress={() => navigation.navigate('ModalStackView')}/>,
    });
}, [deleteAllAlarms, fetchData, navigation]);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda