DEV Community

Martin Soderlund Ek
Martin Soderlund Ek

Posted on

3 1

React Hooks and API Call Sample App

Last time around I wrote about a React sample app with an API call to RandomUser.me.

That version was classic React and now I've updated it to use hooks instead.

With classic React, we used Class components and mutated their internal state via setState when we wanted to do something.

With React hooks, we can use functional components instead, with the State hook useState, which itself is a React function.

We will import useState like this at the top of our file:

import React, { useState } from "react";

Then we'll declare our functional component, like this:

export default function RandomUser() {}

Then we will use EcmaScript 6 (ES6) destructuring and useState to return an array for use in our component:

const [name, setName] = useState([]);

The user and setUser variable names can be anything you want, as long as they are descriptive, of course.

Then we'll use the Effect hook useEffect to initialize our function and insert it into the tree. useEffect "serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API". (React Hooks documentation)

Sweet - useEffect takes care of a lot for us!

useEffect(() => {
fetchRandomUser();
}, []);
view raw RandomUser.js hosted with ❤ by GitHub

As you can see, we have a call to fetchRandomUser(), which will be an async function with our API call.

The complete code looks like this:

import React, { useState, useEffect } from 'react';
export default function RandomUser() {
const [user, setUser] = useState([]);
const [error, setError] = useState([]);
const [isLoading, setIsLoading] = useState(true);
async function fetchRandomUser() {
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;
});
setUser(user);
setIsLoading(false);
});
}
catch(error) {
setError(error);
setIsLoading(false);
}
}
useEffect(() => {
fetchRandomUser();
}, []);
return(
<div>
{error && <p>{error.message}</p>}
{isLoading && <p>Loading...</p>}
{user}
</div>
);
}
view raw RandomUser.js hosted with ❤ by GitHub

Compare this functional component with hooks sample, to the previous class components sample, we now have 48 rows, vs 65 rows before.

Here's the Github repo

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more