1. 9
    Handle Form Submission States with RTK Query's isLoading and isSuccess Values
    1m 29s

Handle Form Submission States with RTK Query's isLoading and isSuccess Values

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet

In this lesson we learn about the isSuccess state that accompanies a successful mutation. We also use the isLoading state from a mutation hook to prevent a user from filling out a form multiple times.

Initially, we display a sent message powered with useState and a setTimeout that gets removed after 2s. In this lesson we display the message after our query's isSuccess value returns true. We also rely on the combination of isLoading || isSuccess to prevent additional form submissions.

Jamund Ferguson: [0:00] With our contact form here, when we send a new message, we receive a short note saying that we have sent the message. We can then immediately start sending messages again.

[0:10] We're going to modify that behavior a little bit. Open up your contact page, and let's destructure a number of additional variables here from our useMakeContactMutation hook. We'll pull in isLoading and isSuccess. Instead of relying on useState here to determine when to show the message, we'll rely on isSuccess. Let's get rid of that, that, get rid of all of this.

[0:33] Now we can say here isSuccess, add the message "Sent message" to the page. Once you've sent the message successfully, show that.

[0:41] This changes the behavior slightly because now, instead of showing the message and having it disappear, we're showing it permanently. Because of this, we also want to prevent the user from resubmitting the form. To do that, we're going to create a new variable called disabled. We're going to make that equal to isLoading || isSuccess.

[0:58] We're just going to apply this to all parts of our form, so input disabled={disabled}, textarea disabled={disabled}, and to our button, disabled={disabled}. As soon as you start submitting your form, isLoading becomes true. You won't be able to use it any longer.

[1:15] As soon as the API comes back successfully, we'll display Message sent. Let's check out that behavior here. Test@test.com. Let's write a small message, hello there. I hit Contact. The form is disabled, and our Message sent is displayed.