Seth Spivey
Seth Spivey

Reputation: 367

How to access map function state and use in external function

I've successfully used the .map function to iterate through the axios GET request data and assign it to the correct element in my map function. However, when I implemented my delete function along with the button onclick element, I receive a the 'Cannot read property '_id' of undefined.

My question is, is it possible to access the map function state of singleuser from my external delete function or to run my delete function within my map function?

// Axios GET request to get the object data from users collection
        axios.get('http://localhost:3000/api/users')
         .then(response => {
           this.setState({ users: response.data });
         })
         .catch(function (error) {
           console.log(error);
         })

// Delete function referencing the ID of the user 
       delete() {
         axios.get('http://localhost:3000/api/users/delete/' + this.state.singleuser._id)
           .then(
              console.log(this.singleuser._id)
           )
           .catch(err => console.log(err))
        }

// Mapping out the state of singleuser from the GET request above          

 {this.state.users.map(function (singleuser, i) {
              const shouldHide = user.group.toString() === singleuser.group.toString()
                 return shouldHide
                    ? null
                    : <tr key={i} style={{ color: '#fff' }}>
                        <td>{singleuser.name}</td>
                        <td>{singleuser.email}</td>
                        <td style={{ display: 'none' }} selected={shouldHide}>{singleuser.group}</td>
                        <td><button onClick={this.delete} className="waves-effect waves-light btn-small red">Edit</button></td>
                      </tr>
             }.bind(this))
            }

Upvotes: 0

Views: 104

Answers (1)

Max
Max

Reputation: 799

You have to use arrow function, because they don't have a local state for example

   delete = (id) => {
     axios.get('http://localhost:3000/api/users/delete/' + id)
       .then((resultOfSuccesfulDeleting) => console.log(resultOfSuccesfulDeleting))
       .catch(err => console.log(err))
    }

 {this.state.users.map(function (singleuser, i) {
              const shouldHide = user.group.toString() === singleuser.group.toString()
                 return shouldHide
                    ? null
                    : <tr key={i} style={{ color: '#fff' }}>
                        <td>{singleuser.name}</td>
                        <td>{singleuser.email}</td>
                        <td style={{ display: 'none' }} selected={shouldHide}>{singleuser.group}</td>
                        <td><button onClick={() => this.delete(singleuser._id)} className="waves-effect waves-light btn-small red">Edit</button></td>
                      </tr>
             }.bind(this))
            }

Upvotes: 1

Related Questions