0

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 ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
MagnusEffect
  • 3,363
  • 1
  • 16
  • 41

2 Answers2

2

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;
fullstack
  • 754
  • 3
  • 20
  • 1
    Caution: This will fail when `data.profile` is undefined, use `data?.profile || {}` so there's an object to destructure from. Same for second line. – Drew Reese Aug 23 '21 at 07:28
0

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

Shubham Waje
  • 781
  • 7
  • 12
  • Like let {bullet,blitz,rapid,classical } = data.perfs, we get bullet as object (eg : bullet : { games": 10755, "rating": 3050, "rd": 45, "prog": 14, } – MagnusEffect Aug 23 '21 at 07:22
  • Yes whatever datatype bullet key of data.prefs has it will render that only, make sure you add check for data.prefs because if its undefined it will break the code while de structuring – Shubham Waje Aug 23 '21 at 12:47