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

419
Visualizações
How to avoid constantly calling api?

How to avoid constantly calling API? I want to avoid that so that the API won't be stressed when calling

useEffect(
  React.useCallback(  () => {
    const task = InteractionManager.runAfterInteractions( async () => {
      const _token =  await AsyncStorage.getItem('@token');
      let UserId = await AsyncStorage.getItem('@UserID')
      setToken(_token);
      fetchParents(UserId, _token);
      fetchStudent(UserId, _token);
      fetchTeacher(UserId, _token);
      UserProfile(UserId, _token)
    });
    return () => task.cancel();
  }, [])
); 


const fetchParents = async (UserId, _token) => {
  try {
    fetch(config.API_URL + '/Parents/Application/Access/10/'+UserId, {
      method: 'GET',
      headers: {
        //Headers
        'Authorization': 'Bearer '+ _token,
        'Content-Type': 'application/json',
      },
    })
    .then((response) =>  response.json().then(data=>({status:response.status, body:data})) )
    .then((response) => {
      if(response.status==200)
      {
        if(response.body.length > 0)
        {
          setParent(response.body[0].udf_Users_IsHaveApplicationAccess)
        }else{
          console.log("err");
        }
      }else{
        console.log("error");
      } 
    });
  
  } catch (e) {
    console.log(e);
  }
}
const fetchStudent = async (UserId, _token) => {
    .....//same code in fetchParents
}
const fetchTeacher = async (UserId, _token) => {
    .....//same code in fetchParents
}
const UserProfile = async (UserId, _token) => {
    .....//same code in fetchParents
}

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are using the useCallabck hook in the wrong way, this hook doesn't need the return statement to cleanup. more information on React's useCallabck documentation.

First, try to remove the return statement from useCallback. Then try to implement the callback outside of your useEffect:

const [task, setTask] = useState(null); // initialize with proper data or leave it blank

const fetchData = React.useCallback(  () => {
    const newTask = InteractionManager.runAfterInteractions( async () => {
      const _token =  await AsyncStorage.getItem('@token');
      let UserId = await AsyncStorage.getItem('@UserID')
      setToken(_token);
      fetchParents(UserId, _token);
      fetchStudent(UserId, _token);
      fetchTeacher(UserId, _token);
      UserProfile(UserId, _token)
    });
    setTask(newTask)
  }, [])


// now, this useEffect run only once after your component did mount
useEffect( () => {
    fetchData()
    // to cleanup tasks on component will mount
    return () => {
      task.cancel();
      setTask(null)  // to remove task from state
  }, [])
);

Also, you can call your APIs with an async function without useCallback hook (which I guess you used to ignore the async call in your useEffect)

async function fetchData () {
  try {
      const newTask = InteractionManager.runAfterInteractions( async () => {
        const _token =  await AsyncStorage.getItem('@token');
        let UserId = await AsyncStorage.getItem('@UserID')
        setToken(_token);
        fetchParents(UserId, _token);
        fetchStudent(UserId, _token);
        fetchTeacher(UserId, _token);
        UserProfile(UserId, _token)
      });
      setTask(newTask)
  } catch (error) {
   // do somethings with error case
  }
}
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