Where does the value count come from in response.json()?

Viewed 41

pretty simple question for some of you out there but, basically I have this line of code

.then(response => response.json())
.then(data => {
      this.setState(Object.assign(this.state.user, { entries: data.count}))
          })

And I have no idea why I have to do data.count to get the number of entries? None of the variables in the object returned are called count. So is it a json thing?

Heres what it returned when I console.log data

{id: "123", name: "john", email: "j@gmail.com", password: "cookies", entries: 14, …}
id: "123"
name: "john"
email: "j@gmail.com"
password: "cookies"
entries: 14
joined: "2020-06-10T21:36:42.041Z"
__proto__: Object

Everything besides proto I have predefined in an object called user.

2 Answers

data.count is possibly undefined for your use-case. But as data has the property entries: 14, so I believe this is what you meant to do,

.then(response => response.json())
.then(data => {
      this.setState(Object.assign(this.state.user, { entries: data.entries /* data.entries instead of data.count */ }))
 })

From the comments: there's your answer — count doesn't come from anywhere, since it isn't there. Calling object.foobar when foobar doesn't exist in JavaScript doesn't throw an error or return null, it returns undefined, which won't break in a lot of cases.

The joys of loose-typing!

const object = {
  foo: 'one',
  bar: 'two'
}
> object.foo
// 'one'
> object.foobar
// undefined

Object.assign simply takes its second argument and copies all its properties onto the first, replacing any in its way. What you've got is the same as:

.then(data => {
  data.count = undefined;
  this.setState(data);
});

Just that you've got it all in one line. Based on how your code is written, I'm not even sure you need this assignment... you may just be able to setState with data directly.

Related