So i got this problem where i get an response from my backend and i parse it to json then call my set function like this
try{
const leaderboardInfo: LeaderboardState = JSON.parse(response);
this.onLeaderboardStateUpdate(leaderboardInfo);
console.log(leaderboardInfo);
}
catch(e){
console.log(`Failed to convert: ${response} into a JS object`);
}
And the console.log gives me this response
So so far so good its the LeaderboardConfig that i want to use to set the state.
My setState
function is just an basic one
onLeaderboardStateUpdate(state: LeaderboardState): void
{
this.setState({leaderboardState: state})
}
and my state looks like this
this.state = {
leaderboardState: {LeaderboardId: 0,LeaderboardName:"",StartDate:"",EndDate: ""}
};
but for some reason this gives undefined so it seems not be able to setState from the json object i have
for your information as well leaderboardState is an interface which looks like this.
export interface LeaderboardState {
LeaderboardId: number
LeaderboardName: string
StartDate: string
EndDate: string
}
What Jai said made me solve it i had to change the try catch to this
try{
const leaderboardInfo = JSON.parse(response);
this.onLeaderboardStateUpdate(leaderboardInfo.LeaderboardConfig[0]);
console.log(leaderboardInfo);
}
catch(e)
{
console.log(`Failed to convert: ${response} into a JS object`);
}
Removing the LeaderboardState interface here and going into LeaderBoardConfiguration which when i had the interface in there messed up.
I suppose you have to send the object instead of array:
this.onLeaderboardStateUpdate(leaderboardInfo[0]);
// [0] will extract the object inside array.-^^^
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.