Efficient way to use display the results from the fetch?

80 views Asked by At

I am started learning reactjs. I have fetch result from the given API https://lichess.org/api/user/nihalsarin2004 which shows the profile of Lichess User. (Here nihalsarin2004). But for using every detail, I have coded them as below:

let fName = JSON.stringify(data?.profile?.firstName);
let lName = JSON.stringify(data?.profile?.lastName);
let totalGames = JSON.stringify(data?.count?.all);
let totalWins = JSON.stringify(data?.count?.win);
let totalDraws = JSON.stringify(data?.count?.draw);
let totalLoss = JSON.stringify(data?.count?.loss);
let userLink = JSON.stringify(data?.url);
.
.
.
.
.
let blitzRating = JSON.stringify(data?.perfs?.blitz?.rating);
let bulletRating = JSON.stringify(data?.perfs?.bullet?.rating);
let rapidRating = JSON.stringify(data?.perfs?.rapid?.rating);
let classicalRating = JSON.stringify(data?.perfs?.classical?.rating);
let chess960Rating = JSON.stringify(data?.perfs?.chess960?.rating);
let antichessRating = JSON.stringify(data?.perfs?.antichess?.rating);
let checkRating = JSON.stringify(data?.perfs?.threeCheck?.rating);
let atomicRating = JSON.stringify(data?.perfs?.atomic?.rating);
let hordeRating = JSON.stringify(data?.perfs?.horde?.rating);

And then using these variables in react components ? Do we any alternative for this ?

2

There are 2 answers

2
Shubham Waje On

You can de-structure them as follows:

if(!data.profile){
    // check if there is data and profile 
    // same for other keys in data obj
    return null
}
let {firstName, lastName} = data.profile
let {all,win, draw, loss} = data.count
// so on...

Note: whenever you are de-structuring any variable from an object make sure you name that variable same as key that you want to extract

for example:
let obj={
name:"John",
age:20,
}

// if you want to destructure obj you can do following
let {name, age}=obj

//variable names in {} should be same as key in obj

1
fullstack On

Use Destructuring Assignment and assign a new variable names in the destructuring:

let { firstName: fName, lastName: lName } = data?.profile;
let { all: totalGames, win: totalWins /* and so on */ } = data?.count;