Interactive Component
At the very end of this tutorial, let's work on a small challenge. First, you'll need to decide to which component you want to add more interactivity. You can choose to make either the delete button or the edit form more interactive. If you feel particularly ambitious, you can work on both.
Once you have made your decision, pick the functionality you want to add. Everything starts from the pending state and goes all the way to awesome posts. Keep in mind that for the most part, the syntax and setup are exactly the same as we already have in the task form custom. Although it might seem a bit tedious because we need to grab a few hooks and set up a separate button, remember that it's mostly the same process. This consistency makes adding interactivity easier in the long run.
In my case, I'm going to add the pending state to my delete button. Essentially, I want to set this up as a client-side component. I'll grab the useFormStatus
hook and move my button into a separate component. This way, we won't encounter errors where we delete items from the list but still display the old items because the deletion takes some time.
Let's try this out. First, navigate to the delete form and set it up as a client-side component:
<DeleteForm />
Next, remember the button needs to be in a separate component. We'll go with something like SubmitButton
:
const SubmitButton = () => {
const { pending } = useFormStatus();
return (
<button disabled={pending}>
{pending ? '...' : 'Delete'}
</button>
);
};
We can copy and paste from TaskFormCustom
, but let's set this up from scratch. Here's our return statement:
return (
<SubmitButton />
);
We want to set up our pending state here as well:
const { pending } = useFormStatus();
Make sure to import useFormStatus
from react-dom
:
import { useFormStatus } from 'react-dom';
Once the button is in place, add the functionality to disable it if pending is true, and display the pending text:
<button disabled={pending}>
{pending ? '...' : 'Delete'}
</button>
And finally, place the submit button below the input:
<input type="submit" />
<SubmitButton />
If everything is correct, you will see the pending text when deleting an item from the list. Let me navigate to the browser and demonstrate:
Notice it was pretty fast, but hopefully, you were able to see the pending state displayed as well. With this in place, we can move on to the next task.
Post a Comment
0Comments