Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda