BONUS: Loading spinner
🐇 TL;DR
- Our
Modalstyle variants are all implemented - Let’s add a touch of delight by adding a loading spinner while performing asynchronous tasks within the modal ♽
🐢 Background
We already have an actions prop type that looks like so:
type ModalProps = {
// ...
actions: {
confirm: {
label: string
action: () => void
}
cancel?: {
label: string
action: () => void
}
}
}
For the context of this workshop, let’s assume that only the confirm would ever lead to asynchronous tasks (creating a new account, deleting a user, processing a payment, …).
We’ll add a isLoading prop to the confirm key of the actions object:
type ModalProps = {
// ...
actions: {
confirm: {
label: string
action: () => void
+ isLoading?: boolean
}
cancel?: {
label: string
action: () => void
}
}
}
The Modal is not responsible for updating and keeping track of that isLoading value. It is simply passed to the modal within the actions prop.
Within the Modal component, this isLoading value can be use to conditionally display a loading spinner, temporarily make the action buttons disabled, and anything else that would depend on a “pending” status.
🏆 Your challenge 🏆
In the Gitpod workspace below:
-
Look at the
LoadingSpinnercomponent at the bottom of theModalcomponent file. -
In the
Modalcomponent markup, display thatLoadingSpinnerconditionally when theisLoadingvalue is true. -
In
src/components/modal/index.tsx, create a newisLoading` boolean piece of state. -
Add that
isLoadingstate to the modal’sactions.confirmprop object. -
Write the code inside the
handleConfirmfunction, which is called when the confirm button is pressed.
This should work, but lead to a subtle UX bug around resetting the isLoading state at the right time.
There’s a solution for this baked in the Headless UI Transition component 👍
✌️ Good luck!
Open in Gitpod →