Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!