Efficient way to use display the results from the fetch? - reactjs

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 ?

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;

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

Related

React-URLSearchParams returning Null object

I am using the following code to retrieve query parameters from URL but URLSearchParams returns an empty object.
PS: uselocation.search returning correct output.
const stringdata = useLocation().search
const queryparameter = new URLSearchParams(stringdata)
console.log("query parameter :", queryparameter)
const query = queryparameter.get('q');
var url_string = `http://localhost:3000/recipes${query}`
You can try using window.location.search over user search params.
That should look something like:
const queryParams = new URLSearchParams(window.location.search);
const query = queryParams.get('q');
let url_string = `http://localhost:3000/recipes${query}`;
The search property returns the querystring part of a URL, including the question mark (?).
const queryParams = new URLSearchParams(window.location.search);
Then you need to check if queryparameter.get('q') exists, otherwise it will return null and will append null to url.
let query;
if(queryParameter.has('q')){
query = queryparameter.get('q');
}
then
var url_string = `http://localhost:3000/recipes/${query}`

TypeError: this is undefined in rect js while passing BigNumber in solana RPC Request

i am getting this is undefined at BN while making RPC request to a function in solana smart contract
'''
let token1Amount = BN(token1_amount);
let token2Amount = BN(token2_amount)
const add_liquidity = await router_program.rpc.addLiquidity(
token1Amount,
token2Amount,
{
accounts: {
// poolAccount: pool_Account.publicKey, //account which stores the individual pair data
userToken1Account: usetoken1_account,
userToken2Account: usetoken2_account,
poolToken1Account: new PublicKey(tokenaccount_1),
poolToken2Account: new PublicKey(tokenaccount_2),
owner: provider.wallet.publicKey,
tokenProgram: TOKEN_PROGRAM_ID,
// systemProgram : SystemProgram.programId ,
// associatedTokenProgram: spl.ASSOCIATED_TOKEN_PROGRAM_ID,
// rent: anchor.web3.SYSVAR_RENT_PUBKEY,
tokensProgram: TOKEN_ID,
// poolProgram: pair.programId,
// pairAccount: pairAccount.publicKey
},
// signers: [provider]
}
);
'''
This is a shot in the dark, but I think you need new so that your BNs have a this context, so instead try:
let token1Amount = new BN(token1_amount);
let token2Amount = new BN(token2_amount);

Get the specific data (seatType: & seatTypeId:) from an Array React

I have an Array that has the following data & I want to get the specific attributes to variables which I need to pass through URL parameters.
Array
MovieSeatList:[
adultPrice: 350
childAvailable: true
childPrice: 280
seatRows: [Array(5)]
seatType: "ODC"
seatTypeId: 536
]
code:
render() {
const {MovieSeatList, dataLoaded} = this.state;
console.log(MovieSeatList)
// MoviedatatoPlan = MovieSeatList
console.log(MovieSeatList)
console.log(movieData)
}
It would be better if I can get the following attributes to variables that will be passed in URL parameters.
seatType:
seatTypeId:
let seatType = MovieSeatList.map(a => a.seatType);
let seatTypeId = MovieSeatList.map(b => b.seatTypeId);

TypeError: Cannot read property 'fetchMembers' of undefined

i got this erroe even the command is working fine
(node:1907) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'fetchMembers' of undefined
client.on('message', async message => {
let guild = await message.guild.cache.fetchMembers();
let roleID= '644235497169748037';
let roleID1= '615852982734684181';
let roleID2= '615852983330013212';
let roleID3= '615852992230588427';
let roleID4= '722513324151144552';
let memberCount = guild.roles.get(roleID).members.size;
let memberCount1 = guild.roles.get(roleID1).members.size;
let memberCount2 = guild.roles.get(roleID2).members.size;
let memberCount3 = guild.roles.get(roleID3).members.size;
let memberCount4 = guild.roles.get(roleID4).members.size;
let memberCountChannel = guild.channels.get("733035179756486737")
let memberCountChannel1 = guild.channels.get("732530240420839464")
let memberCountChannel2 = guild.channels.get("732530312713863178")
let memberCountChannel3 = guild.channels.get("732530713898909746")
let memberCountChannel4 = guild.channels.get("732530791686602833")
memberCountChannel.setName("Guild Members: " + memberCount)
memberCountChannel1.setName("Wizard: " + memberCount1)
memberCountChannel2.setName("Witch: " + memberCount2)
memberCountChannel3.setName("Shai: " + memberCount3)
memberCountChannel4.setName("Compass: " + memberCount4)
});
Discord JS v12 introduces the concept of managers, you will no longer be able to directly use collection methods such as Collection#get on data structures like Client#users. You will now have to directly ask for a cache on a manager before trying to use collection methods.
You need to change:
guild.roles.get(roleID)
// to
guild.roles.cache.get(roleID)
and:
guild.channels.get(channelID)
// to
guilds.channels.cache.get(channelID)
Another error I saw in your code is that you are trying to access the property cache of Guild, which is nonexistent (message.guild.cache.fetchMembers()).
You'll have to use:
message.guild.members.fetch()

Can I Get The Object Name in A Loop? - Swift 2

I've written this loop. But, I'm wondering if I can do without the name property and just reference the name of the object?
class Param {
var name = ""
var value = 0.0
var skip = -1
}
let depth = Param()
depth.name = "depth"
let tankPressure = Param()
tankPressure.name = "tankPressure"
let time = Param()
time.name = "time"
let tankCapacity = Param()
tankCapacity.name = "tankCapacity"
let litresPerMinute = Param()
litresPerMinute.name = "litresPerMinute"
let params = [depth, tankPressure, time, tankCapacity, litresPerMinute]
for param in params {
let outlet = "\(param.name)Outlet.text!"
print(outlet)
}

Resources