Adding an animated state to our Remix form

Now that we’ve got our form displaying error, we nonetheless have one slight draw back.

For example our type takes fairly some time to load. Some customers is perhaps impatient and click on the submit button a number of occasions and even change the inputs.

Let’s emulate that by introducing a “sleep” in our motion.

export const motion = async ({ request }) => {
  // Sleep...
  await new Promise((r) => setTimeout(r, 1000));

  // All the opposite stuff
Enter fullscreen mode

Exit fullscreen mode

Now our code will at all times wait 1000 milliseconds.

Utilizing the Remix useTransition hook

Apart from the hooks, we already used, Remix offers us a useTransition hook.
We are able to hook into the truth that the shape is busy with one thing with this hook.

In our case, we need to disable all the shape fields and alter the textual content on the button, so the person is aware of one thing is going on.

First, we load the hook inside our render.

import { useTransition } from '@remix-run/react';

export default operate NewPost() {
  const transition = useTransition();

  // Our render
Enter fullscreen mode

Exit fullscreen mode

Then for the render half we will wrap our type parts inside a fieldset so we will rapidly disable all of them:

<Kind technique='put up'>
  <fieldset disabled={transition.state === 'submitting'}>
    // Our type fields
Enter fullscreen mode

Exit fullscreen mode

You possibly can see we hook into the transition state, and if that’s submitting, we disable the shape.

Subsequent, we will change our button to replicate the motion as properly.

  className='rounded bg-blue-500 py-2 px-4 text-white hover:bg blue-600 focus:bg-blue-400 disabled:bg-blue-300'
  {transition.state === 'submitting' ? 'Creating...' : 'Create put up'}
Enter fullscreen mode

Exit fullscreen mode

This is identical idea of utilizing the state to find out which textual content to point out.

If we run our code, we must always get the next end result:

You may as well discover the finished code pattern on this GitHub branch.

Thanks for studying, and let’s join!

Thanks for studying my weblog. Be happy to subscribe to my e-mail e-newsletter and join on Facebook or Twitter

Add a Comment

Your email address will not be published. Required fields are marked *