Skip to content

Commit 30aa9a0

Browse files
committed
Handle Errors
1 parent bce4199 commit 30aa9a0

File tree

2 files changed

+71
-10
lines changed

2 files changed

+71
-10
lines changed

src/App.js

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,44 @@
1-
import React from "react";
2-
import Search from "./components/Search3";
1+
import React from 'react';
2+
import Search from './components/Search';
33

4-
function App() {
5-
return <Search />;
4+
class App extends React.Component {
5+
state = {
6+
user: null,
7+
error: null,
8+
};
9+
10+
fetchUserData = async username => {
11+
try {
12+
const res = await fetch(`https://api.github.com/users/${username}`);
13+
if (res.ok) {
14+
const data = await res.json();
15+
16+
return this.setState({
17+
user: data,
18+
});
19+
}
20+
21+
const error = (await res.json()).message;
22+
23+
this.setState({
24+
error,
25+
});
26+
} catch (err) {
27+
this.setState({
28+
error: 'There was some error',
29+
});
30+
}
31+
};
32+
33+
render() {
34+
const { error } = this.state;
35+
return (
36+
<div>
37+
<Search fetchData={this.fetchUserData} />
38+
{error && <p className="text-danger">{error}</p>}
39+
</div>
40+
);
41+
}
642
}
743

844
export default App;

src/components/Search.js

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,47 @@
11
import React from "react";
22

33
class Search extends React.Component {
4-
state= {
5-
username: '',
6-
}
4+
state = {
5+
username: ""
6+
};
77

88
handleUserNameChange = e => {
9-
const value = e.target.value;
9+
const value = e.target.value;
1010

1111
this.setState({
12-
username: value,
12+
username: value
1313
});
1414
};
1515

1616
render() {
17+
const { fetchData } = this.props;
1718
const { username } = this.state;
1819

19-
return <input value={username} onChange={this.handleUserNameChange} type="text" name="username" placeholder="Enter username" />;
20+
return (
21+
<div className="bg-dark">
22+
<div className="container py-5">
23+
<div className="row">
24+
<div className="col-8 offset-2 text-center">
25+
<div className="row">
26+
<div className="col-9">
27+
<input
28+
className="form-control"
29+
value={username}
30+
onChange={this.handleUserNameChange}
31+
type="text"
32+
name="username"
33+
placeholder="Enter username"
34+
/>
35+
</div>
36+
<div className="col-3">
37+
<button onClick={() => fetchData(username)} className="btn btn-large btn-success">Search</button>
38+
</div>
39+
</div>
40+
</div>
41+
</div>
42+
</div>
43+
</div>
44+
);
2045
}
2146
}
2247

0 commit comments

Comments
 (0)