0

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

enter image description here

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.

2
  • Did you bind thisto onLeaderboardStateUpdate? Commented Nov 12, 2018 at 9:58
  • Please provide the full error log. Also recheck the method bindings with this as Matthi said Commented Nov 12, 2018 at 10:07

1 Answer 1

2

I suppose you have to send the object instead of array:

this.onLeaderboardStateUpdate(leaderboardInfo[0]); 
// [0] will extract the object inside array.-^^^
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.