I know there are errors in my code but being a React newbie, I can't figure them out. My goal is to fetch users from the api
and render their email and bio on screen once the button is pressed.
class App extends Component {
state = {
users: []
}
async getUser(e) {
e.preventDefault();
const username = e.target.elements.username.value;
const profileResponse = await fetch(`https://api.github.com/users/${username}?client_id=${client_id}&client_secret=${client_secret}`);
const user = await profileResponse.json();
this.setState({ users: this.state.users.concat([user]) });
}
render() {
return (
<div className="App">
<h1>Search users</h1>
<p>Enter a username to fetch a user.</p>
<form onSubmit={this.getUser}>
<input
type="text"
name="username"
placeholder="GitHub username"
/>
<button>Find User</button>
</form>
{ this.state.users.length > 0 && this.state.users.map((user) => <p key={user.login}>{user.email, user.bio}</p>) }
</div>
);
}
}
export default App;
The error:
Objects are not valid as a React child (found: object with keys {login, id, avatar_url, gravatar_id, url, html_url, followers_url, following_url, gists_url, starred_url, subscriptions_url, organizations_url, repos_url, events_url, received_events_url, type, site_admin, name, company, blog, location, email, hireable, bio, public_repos, public_gists, followers, following, created_at, updated_at}). If you meant to render a collection of children, use an array instead.
Running your example, I received the following error :
Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined
Transforming getUser
to an arrow function fixed it : getUser = async (e) => {}
Further reading : https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56
Second problem :
{user.email, user.bio}
in render won't work replace with {user.email} {user.bio}
This is the issue:
{user.email, user.bio}
The solution is:
{user.email}, {user.bio}
Also, you need to make sure that user.email and user.bio are not objects.
You need to handle the case where the response that you receive from the API is not a user object, for example if the user you are looking for doesn't exist.
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.