Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
REACT: A simple example of doing asynchronous work inside of a useEffect()
/**
* A React component:
* r1. name starts with a Capital letter
* r2. gets a single argument, typically referred to as "props", that is an object containing all properties passed in
* r3. can use hooks (useState, useEffect, useRef, etc...)
* r4. returns JSX
**/
/** r1. name starts with a Capital letter */
/** r2. gets a single argument, typically named "props" */
const MyUserComponent = (props) => {
/** r3. can use hooks */
const [users, setUsers] = useState(); // defaults to undefined...on purpose!
// this is a SYNCHRONOUS function
const getUserList = () => {
// define an ASYNC function -- assume this function might take a LONG TIME (a second or more!)
const getUserListFromAPI = async () => {
// assume system has a "proxy" setting so it knows server URL prefix
let response = await fetch("/users");
// extracts the body of response and parses it as JSON data
let userData = await response.json();
// now put the retrieved data into state,
// and when that state gets updated (asynchronously -- a LONG TIME from now)
// then this component will re-render itself
setUsers(userData);
}
// call the async function
getUserListFromAPI();
}
// this will only call getUserList() on first
useEffect(getUserList, []);
/** r4. return JSX */
if (! users) { // users is initially "falsey" because we left it blank
return <p>Loading users. . .</p>
} else {
return <p>We have {users.length} users loaded!</p>
}
};
const MyUserComponent = (props) => {
const [users, setUsers] = useState();
const getUserList = () => {
const getUserListFromAPI = async () => {
let response = await fetch("/users");
let userData = await response.json();
setUsers(userData);
}
getUserListFromAPI();
}
useEffect(getUserList, []);
if (! users) {
return <p>Loading users. . .</p>
} else {
return <p>We have {users.length} users loaded!</p>
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment