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

183
Visualizações
How can I call a function only once in typescript

I have been trying to start using typescript for react native but it has not been easy ride so far, finding it difficult to perform common function like fetch an api once on screen load, below is the current function am using but I dont want to use time outs plus its not even working properly(it has to wait for the actual time I set before it runs and its bad for android), I would like to call the function only once when the page loads, I have also tried using if else statements but I dont know why it not just working on typescript.

 (function(){  
   setTimeout(function () {
const newsUrl = 'http://172.20.10.4:8000/mobile/news';
    return fetch(newsUrl, {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
             'Cache-Control': 'no-cache'
          }
        })
        .then((response) => response.json())
        .then((data) => {
            let newArr = [...data];
            setProducts(newArr);
            //console.log(data);
            alert(38783763);
          
        })
        .catch((error) => {
            alert(error);
           console.error(error);
         });
       }, 200); 

}.call(this));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use the useEffect hook and pass an empty array the fetch data once on load.

useEffect(() => {
  fetch(newsUrl, {
          method: 'GET',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
             'Cache-Control': 'no-cache'
          }
        })
        .then((response) => response.json())
        .then((data) => {
            let newArr = [...data];
            setProducts(newArr);
        })
}, []);
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