c-poulsen c-poulsen - 1 year ago 80
Javascript Question

Undefined is not an object in .map

I'm working on a react app, and I try to iterate over a data block. The block has a unixtime that I want to do some calculations on, but when I call the function on the object I get the error

_getTime(time) {
if (time === 0) {
return '1';
} else if (time === 2) {
return '2';
} else {
return 'stuff';

render: function() {
return (
<div className="container-fluid">
<div className="row">
<div className="col-md-12 text-center">
{this.state.daily.map(function(day) {
return (
<div key={day.time} className="key col-md-12">
<div className="col-md-3">{this._getTime(day.time)}</div>
<div className="col-md-3">{day.icon}</div>
<div className="col-md-3">{day.apparentTemperatureMax} / {day.apparentTemperatureMin}</div>

The problem is this line
<div className="col-md-3">{this._getTime(day.time)}</div>
and when I place it outside the map function it all works.

Any help will be appreciated

Answer Source

That's because this is determined at function call time, not at function write time. Your anonymous function, called by .map() when it iterates the collection for you, doesn't have a this.

There are a couple of ways to solve this, since you're obviously using babel, I can assume you're using ES6, in which case, changing your anonymous function into an arrow function expression, will do the trick:

this.state.daily.map(day => {
  // ...

Alternatively, have a look at .bind(), as well as the second argument to .map().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download