mikha
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 ,
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?
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"}
]
}
I defined my classes/interface like this,class Result {
users: user[] //array to hold each user
}
class user{
name: string;
email: string;
}
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);
})
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.