Попробуй это.Я исправил твой код.Я объяснил в коде как комментарии для вашего понимания
PFB исправленный код
import React, { Component } from 'react';
import './App.css';
// App component
class App extends Component {
constructor(){
super();
this.state = {
username: '',
id: '',
url: '',
avatar_url: '',
user: ''
}
}
getUser(username){
return fetch(`https://api.github.com/users/${username}`)
.then(response => response.json())
.then(response => {
return response;
})
}
async handleSubmit(e){
e.preventDefault();
const user = await this.getUser(this.refs.username.value);
//You can use user.ok to check whether the response is ok if yes set the user details otherwise user is not found so set the values to default one
// I have taken additional variable to show error message when user is not found. If user found I will set user to "" empty string other wise I am setting user not found value to user.
if(user.ok){
this.setState({
username: user.login,
id: user.id,
url: user.url,
avatar_url: user.avatar_url,
user: ''
});
}else{
this.setState({
username: '',
id: '',
url: '',
avatar_url: '',
user: 'not found'
});
}
}
render() {
const { user, username,avatar_url, id } = this.state;
// The above line reduces repeating this.state.xxx in render method
return (
<div className="app">
<header className="app-header">
<h1>Github Finder</h1>
</header>
<form onSubmit={e => this.handleSubmit(e)}>
<label className="label-finder">Search github user: </label>
<input className="input-finder" ref='username' type="text" placeholder='Enter Username' />
</form>
<div className="user-data">
{/* You can directly check if user == "not found" then show error message using && operator*/}
{user == 'not found' && (
<div>
<img alt="user-dp" src={avatar_url} width=220 />
<p><strong>Username: </strong>{username}</p>
<p><strong>User id: </strong>{id}</p>
<p><strong>Profile URL: </strong>
<a href={"https://github.com/" + username}>{"https://github.com/" + username}</a>
</p>
</div>
)}
</div>
</div>
);
}
}
export default App;