how to pass a api response value to onclick function

Viewed 359

when i click the listgroup.item i want the userid to be passed to the onclick funtion am getting the value as undefined.if i get the value in the handleclick i will pass the value as props to another component and get the complete detail of the user. any solutions thanks in advance

import React, { Component } from 'react'
import axios from 'axios'
import ListGroup from 'react-bootstrap/ListGroup';

 class ViewUsers extends Component {
    constructor(props) {
        super(props)

        this.state = {
             User:[],
             error:[],
             Id:0

        }
        this.handleclick = this.handleclick.bind(this)
    }
    handleclick = (User) => {
        this.setState({
            Id:User.userid
        })
        this.props.history.push('/Viewuserbyid')
        console.log(this.Id);
    }
    componentDidMount(){
        const header ={
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        }
        axios.post('https://localhost:/api/getallusers',{
            header:header
        })
        .then(res => { 
            console.log(res)
            this.setState({
                User:res.data
            })
        })
        .catch(Error =>{
            this.setState({
                error:'Error retriving data'
            })
            console.log(Error)
        })
    }
    render() {
        const {User,error} = this.state;
        return (
            <div style={{height:"100%"}}> 
                {/* onChange={(event)=>this.setState({keyword:event.target.value})} */}
          <input type="text" placeholder="search" className="form-control form-control-sm"  />
          <button>search</button>
           {
               User.length ? User.map(User => (
               <ListGroup key={User.userid}>
                   <ListGroup.Item onClick={this.handleclick.bind(this,User.userid)}>
                       Name : {User.name} <br/> AccountNumber : {User.accountNumber}
                   </ListGroup.Item>
               </ListGroup >) : null
           }
           {
                error ? <div>{error}</div> : null
           }

            </div>
        )
    }
}

export default ViewUsers

2 Answers

Will this work?

<ListGroup.Item onClick={() => this.handleclick(User.userid)}>

And maybe use this in the click handler:

handleclick = (User) => {
    this.setState({
        Id:User.userid,
        // might want to update User also by uncommenting the next line
        // User,
    }, () => {
        console.log(this.state.Id)
        console.log(this.state.User)
    })
    this.props.history.push('/Viewuserbyid')
}

Try with onClick = {()=>{this.handleclick(user.userid)}} and handleclick = id => { this.setstate({id:id}) }

Related