A while back I created a small and simple React app in order to fetch a random user from the RandomUser.me API.
You can find the React app on my GitHub: hello-react
I have a RandomUser component which simply looks like this:
import React, {Component} from 'react'; | |
class RandomUser extends Component { | |
constructor() { | |
super(); | |
this.state = { | |
user: [], | |
isLoading: false, | |
error: null | |
} | |
} | |
componentDidMount() { | |
this.setState({ isLoading: true }); | |
this.fetchRandomUser(); | |
} | |
fetchRandomUser = async() => { | |
try { | |
await fetch('https://randomuser.me/api/') | |
.then(results => { | |
return results.json(); | |
}) | |
.then(data => { | |
let user = data.results.map((user) => { | |
let userElm = ''; | |
if (typeof user !== undefined && typeof user.name !== undefined && typeof user.picture != undefined) { | |
userElm = <div key={user}> | |
<h2>{user.name.first} {user.name.last}</h2> | |
<img src={user.picture.large} alt="" /> | |
</div>; | |
} | |
return(userElm) | |
}); | |
this.setState({user: user, isLoading: false}); | |
}); | |
} | |
catch(error) { | |
this.setState({ error: error, isLoading: false }); | |
} | |
} | |
render() { | |
let { user, isLoading, error } = this.state; | |
if (error) { | |
return <p>{error.message}</p>; | |
} | |
if (isLoading) { | |
return <p>Loading...</p>; | |
} | |
return ( | |
<div> | |
{user} | |
</div> | |
) | |
} | |
} | |
export default RandomUser; |
We fetch a user from the API and present the user's name and picture, if present.
In our App.js file we then return the RandomUser
component together with some HTML:
import React from 'react'; | |
import RandomUser from './RandomUser'; | |
import './App.css'; | |
function App() { | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<RandomUser /> | |
</header> | |
</div> | |
); | |
} | |
export default App; |
In the VS Code terminal we run the npm start
command and our React app is compiled and we can look at it in the browser on http://localhost:3000/.
After commit to Github, I got a few security messages back, as expected.
First, I checked React version with this command:
npm list react
and got -- react@16.8.6
back, which isn't the latest version. To install latest React version, I had to run this command:
npm install --save react@latest
And then update packages in the React app with this command:
npm audit fix
I also manually had to update lodash.template
to 4.5.0:
npm install --save lodash.template@latest
You can find the React app on my GitHub: hello-react @ dileno
Top comments (0)