For my latest project, I wanted to create the ability to favorite and unfavorite a breathing technique. When I first decided to tackle this in React, I thought I could create two separate callback functions to pass into my
onClick handler (
unfavoriteBT()). However, I later realized that I could use if/else statements to toggle the favoriting functionality. So, I decided to use one function to handle both:
I would need to chain two fetch requests, and the second one would depend on the data returned from the first. However, since fetch requests are asynchronous, the second fetch request would fail because it would not receive data from the first fetch in time. In other words, the second request continues to execute without waiting for the first fetch to finish.
If you take a look below, you’ll see that I use
setState to update the state for the
favorite object. However, the second fetch request, which uses a PATCH, depends on the favorite object’s
fav_id key is never assigned.
await feature, which helps us mimic synchronicity. When you use the
async keyword with a fetch request, that indicates that the async function will stop executing the rest of the code until the promise is resolved. Take a look below, where I label the
toggleFavBT() and precede each fetch request with
That means that the second fetch request waits for the first promise to resolve, so it updates state for the favorite object. Then, the second fetch is able to successfully update the