简体   繁体   中英

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));

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);
        })
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM