André Vigneaux
André Vigneaux

Reputation: 33

javascript array.includes doesn't work right in react

First of all, I'm a newbie at frontend, so my knowledge about javascript + react is based on tutorials.

I have an object that is set to the component properties. This object has an array as a property.

So inside the component, either in a function or the render method, if a write a console.log(object.property)

It prints the array, no error.

But if I try to use the .includes method

console.log(object.property.includes("string"))

it throws the following error:

react-dom.development.js?cada:12404 Uncaught TypeError: Cannot read property 'includes' of undefined

so how does the array turn into undefined just for using this method?

The workaround I found, is something like this:

   render() {
    let self = this;
    let user;
    return(
      {
        this.props.otherarray.map(function(var) {
            self.user = self.props.object.property.includes("string") 
        })
        console.log(this.user)
      }
    );
   }

and then it works.

What am I missing? Is it something about javascript context or react stuff?

Upvotes: 1

Views: 7535

Answers (1)

devserkan
devserkan

Reputation: 17608

console.log output is misleading you. I guess object is coming from an async job and you are seeing the array in the first render as undefined and it the second render as it is. Being undefined is not a problem but if you try to use a method on a nonexistent property like map, includes is a problem and you get the error quoted in your question. So, you need to check the existence of this property. I don't know your component setup but here is an example:

const object = {
  property: [ "foo", "bar", "baz" ]
}

const fakeRequest = () => new Promise( resolve =>
  setTimeout(() => resolve(object),1000)
);

class App extends React.Component {
  state = {
    object: {},
  }
  componentDidMount() {
    fakeRequest().then(this.setState({object}))
  }
  render() {
    const { object } = this.state;
    object.property && console.log(object.property.includes("foo"))
    return <div>Foo</div>;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 1

Related Questions