Link to home
Start Free TrialLog in
Avatar of mikha
mikhaFlag for United States of America

asked on

how to define your class/type in typescript read json data?

I am working on a typescript react js project. I am using fetch api to call an REST api , which returns response like this ,


data = { 
   "users":[       
       {"name":"sam", "email":"sam@gmail.com"},       
       {"name":"henry", "email":"henry@gmail.com"},    
       {"name":"John", "email":"john@gmail.com"},     
       {"name":"Bob", "email":"bob32@gmail.com"}
    ]
}

Open in new window

I defined my classes/interface  like this,

class Result {
    users: user[]  //array to hold each user
}
 
class user{
    name: string;
    email: string;
}

Open in new window


I declared userlist of type Result, to save the response data. as I have declared my Result class with "users" variable of type user[] array which matches my json response , which has users array list in it.
assigning userlist: data below in fetch call , should populate my userlist variable correctly?
such that i can iterate like this . is this correct? 

userlist.users.foreach(element => {
  console.log(element.name); 
})

Open in new window


 const userlist = Result;

// GET Request.
fetch('https://api.github.com/users/...')    // Handle success   
 .then(response => response.json())  // convert to json   
 .then(data => this.setstate({ userlist : data });)    //print data to console    
.catch(err => console.log('Request Failed', err)); // Catch errors

Open in new window





ASKER CERTIFIED SOLUTION
Avatar of Shinesh Premrajan
Shinesh Premrajan
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial