File tree Expand file tree Collapse file tree 2 files changed +79
-0
lines changed Expand file tree Collapse file tree 2 files changed +79
-0
lines changed Original file line number Diff line number Diff line change 1+ <!DOCTYPE html>  
2+ < html  lang ="en "> 
3+ < head > 
4+     < meta  charset ="UTF-8 "> 
5+     < meta  name ="viewport " content ="width=device-width, initial-scale=1.0 "> 
6+     < title > Document</ title > 
7+ </ head > 
8+ < style > 
9+     * 
10+         margin :  0 ;
11+         padding :  0 ;
12+         box-sizing :  border-box;
13+     }
14+ 
15+     body  {
16+         padding :  1rem  ;
17+         display :  grid;
18+         place-items :  center;
19+     }
20+ 
21+     .post  {
22+         margin :  1rem  ;
23+         padding :  1rem  ;
24+         border :  0.125rem   solid black;
25+     }
26+ 
27+     h1  {
28+         padding :  1rem  ;
29+     }
30+ </ style > 
31+ < body > 
32+     < button  id ="fetch-api-button "> Click To Fetch</ button > 
33+     < h1 > API Titles</ h1 > 
34+     < div  class ="append-titles "> 
35+     </ div > 
36+ 
37+ 
38+ < script  src ="./script.js "> </ script > 
39+ </ body > 
40+ </ html > 
Original file line number Diff line number Diff line change 1+ 
2+ const  postApi  =  "https://jsonplaceholder.typicode.com/todos" ; 
3+ 
4+ // Fetch API Function 
5+ async  function  fetchTodo ( apiUrl )  { 
6+     try  { 
7+         const  response  =  await  fetch ( apiUrl ) ; 
8+         if  ( ! response . ok )  { 
9+             throw  new  Error ( 'Network response was not ok' ) ; 
10+         } 
11+         const  json  =  await  response . json ( ) ; 
12+         return  json ; 
13+     }  catch  ( error )  { 
14+         console . error ( 'There was a problem with the fetch operation:' ,  error ) ; 
15+     } 
16+ } 
17+ 
18+ 
19+ // Append data in DOM  
20+ function  appendData ( data )  { 
21+     const  container  =  document . querySelector ( '.append-titles' ) ; 
22+     data . forEach ( ( item )  =>  { 
23+         const  newTitle  =  document . createElement ( 'div' ) ; 
24+         newTitle . className  =  'post' ; 
25+         newTitle . innerHTML  =  item . title ; 
26+         container . appendChild ( newTitle ) ; 
27+     } ) ; 
28+ } 
29+ 
30+ // Helper function to store data from fetch function and pass on to appendData function 
31+ async  function  clickHandler ( )  { 
32+     const  data  =  await  fetchTodo ( postApi ) ; 
33+     appendData ( data ) ; 
34+ } 
35+ 
36+ window . onload  =  ( )  =>  { 
37+     const  button  =  document . getElementById ( 'fetch-api-button' ) ; 
38+     button . addEventListener ( 'click' ,  clickHandler ) ; 
39+ } 
 
 
   
 
     
   
   
          
    
    
     
    
      
     
     
    You can’t perform that action at this time.
  
 
    
  
    
      
        
     
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments