Lesson 2. Trigger side effects with useEffect 3. Making HTTP requests
HTTP requests are probably the most common side effects you can encounter in a
web application. When using the fetch function (available in all browsers),
you get as result a promise; what we’ll see here can be applied to any function
returning a promise.
This component performs an HTTP request to an external API, and stores the result in a local state:
Result
The person state is initialized with undefined, and when the fetch promise
is resolve we put the result inside it.
Notice that, to avoid updating the state after the component is unmounted, we
use an active flag in the useEffect.
If the component allows us to get info for several people using a personId
prop, this active flag also ensures that we call setPerson only for the
current person ID, not any of the previous ones for which we triggered an HTTP
request.
const MyComponent = ({ personId }) => {const [person, setPerson] = useState(undefined)useEffect(() => {let active = truefetch(`https://swapi.dev/api/people/${personId}/`).then((res) => res.json()).then((person) => {if (active) {setPerson(person)}}).catch((err) => console.error(err))return () => (active = false)}, [personId])return <p>{person ? person.name : 'Loading…'}</p>}
In the lesson 3, we’ll see a useful pattern to handle HTTP requests (and asynchronous operations in general) more properly.