-1

I want to get the last item of a json response.

When i do console.log(this.state.details.sessions) it shows me following json object.

[{"login_time": "12-04-2021 20:52:29", "logout_time": ""}, {"login_time": "12-04-2021 20:54:53", "logout_time": "12-04-2021 20:55:13"}] 

But if try to get the length of this item like: Object.keys(this.state.details.sessions).length i get this following error:

undefined is not an object (evaluating 'Object.keys(data.sessions)')

const {number} = this.props.route.params;
database().ref('/numbers/'+number.replace('+', ''))
          .on('value', (snapshot) => {
            const userObj = snapshot.val();
            this.setState({
                details: userObj
          })
});

console.log(Object.keys(this.state.details.sessions).length);

What can be the problem?

user3786081
  • 177
  • 2
  • 13
  • `data.sessions[data.sessions.length - 1];` to get the last item – DecPK Apr 13 '21 at 15:25
  • @decpk just updated the post, it still shows me a error. "(undefined is not an object (evaluating 'data.sessions.length') – user3786081 Apr 13 '21 at 15:30
  • So it was [how-do-i-return-the-response-from-an-asynchronous-call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) after all. I got a bit confused, because the structure was nested, and you are using `Object.keys` on an array, but oh well. – ASDFGerte Apr 13 '21 at 15:31
  • @ASDFGerte can you please explain me how to do it in the right way? – user3786081 Apr 13 '21 at 15:42

1 Answers1

0

in the very first this.state.details.sessions is undefined, you cannot use Object.keys on that

after you set data into that

this.setState({
  details: userObj,
});

this.state.details.sessions is actually an array

Dinh Huynh
  • 204
  • 1
  • 5