I was able to get all users and (through button clicks) to get a particular user by id. But I cannot figure out a way to get a user from an input.
Can anybody please suggest how to achieve that?
This is my code:
import React, {Component} from 'react'
class App extends Component {
constructor(props){
super(props)
this.onHandleUsers = this.onHandleUsers.bind(this)
this.state = {
isLoaded: false,
users: []
}
}
onHandleUsers() {
fetch("http://localhost:3000/api/users")
.then(res => res.json())
.then(result => {
this.setState({
isLoaded: true,
users: result
})
})
.catch(e => console.log(e))
}
onHandleCurrentUsers(userId) {
const data = {userId: userId}
fetch("http://localhost:3000/api/user", {
method: 'POST',
headers: { "Content-Type": "application/json"},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(result => {
this.setState({
isLoaded: false,
currentUser: result
})
})
.catch(e => console.log(e))
}
render() {
const {currentUser} = this.state
return (
<div>
<button onClick={this.onHandleUsers}>Gauti vartotojus</button>
<ul>
{
this.state.isLoaded && this.state.users.map(item => {
return (
<li>name : {item.name} <br>
</br>surname: {item.surname}</li>
)
})
}
</ul>
<button onClick ={e => this.onHandleCurrentUsers(1)}>get first user </button>
<button onClick ={e => this.onHandleCurrentUsers(2)}>get second user </button>
<div>
{
currentUser && <div>{currentUser.name} {currentUser.surname}</div>
}
</div>
<div> </div>
</div>
)
}
}
export default App
it's fairly simple, all you have to do is to have an input that handles the desired user's id:
<input name='userId' onChange={this.handleUserChange} />
and we define this.handleUserChange like this:
handleUserChange = (e) => {
const {value} = e.target
this.onHandleCurrentUsers(value)
}
and basically you pass the id of a user to our input and it changes the current user!
Hello this is indeed helpful, but i already had this one done, thing is with this one it instantly brings the current user on input, my problem is that i have to get a button to click and only then get the value. I m trying to do the same with ref as you did but i cannot bring back ref after my input atm..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.