RoffyBC
RoffyBC

Reputation: 189

Accessing ID of object in Array of objects,ReactJS

I'm Trying to Retrieve ._id From mongoDB Collection By using map loop but the problem is it's giving me undefined. Any suggestions?

render() {
    const {itemsPerPage, currentPage, todos} = this.state;
    const end = currentPage * itemsPerPage
    const start = end - itemsPerPage
    const currentItems = todos.slice(start, end);
    console.log('--------currentItems', currentItems);
    return <div className={"App"}>
        <div className="App-header">
            <h2>Welcome to To-Do List App</h2>
        </div>
        <input ref={this.inpRef} onKeyPress={this.handleKeyPress} name={''} type='text'/>
        <button onClick={() => this.addItem()} className={'btn btn-primary'}>Add</button>
        <ul>
            {
                currentItems.map(todoItem => {
                    return <ListItem
                    key={todoItem._id}
                    todoItem={todoItem}
                    deleteItem={this.deleteItem}
                    editItem={this.editItem}
                    submitEdit={this.submitEdit}
                />})
            }
            <div>
                {this.renderPagination()}
            </div>
        </ul>
    </div>
};

}

CurrentItems output: [{…}, {…}] 0: {_id: "5ee33e6a5398c70ccf57f684", todo: "a", checked: false, __v: 0} 1: {_id: "5ee33e775398c70ccf57f685", todo: "z", checked: false, __v: 0} length: 2 __proto__: Array(0)

Upvotes: 1

Views: 29

Answers (1)

gazdagergo
gazdagergo

Reputation: 6691

It might be some async issue with the data. Try to escape rendering until currentItems contains data.

render() {
  ...
  {currentItems.length && <ul>
    {currentItems.map(todoItem => {...})}
   </ul>}
  ...
}

Upvotes: 1

Related Questions