Skip to content

Instantly share code, notes, and snippets.

@gregfenton
Last active February 26, 2021 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregfenton/6b3211939db5aca69e7420eda16946a0 to your computer and use it in GitHub Desktop.
Save gregfenton/6b3211939db5aca69e7420eda16946a0 to your computer and use it in GitHub Desktop.
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