Magic of Type Inference in React Modals with EasyModal
Published: 2023-12-22 15:12:40



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/frsqnoperfndqxslnrhj.png)

Are you a React developer who has struggled through the verbose and convoluted patterns of managing modal dialogs? Have you ever longed for a way to seamlessly integrate modals into your application logic while maintaining crisp type-safety with TypeScript? Enter **EasyModal**—a revolutionary tool that not only simplifies modal management but astonishes with its ability to infer types gracefully.

### Level Up Your Modals with Promises and TypeScript

EasyModal's philosophy is simple: Treat modals as asynchronous events and manage their lifecycle through promises. This approach leads to cleaner, more predictable code where the handling of modal actions like opening, updating, and closing becomes as natural as writing an `async` function.

With TypeScript, EasyModal takes the possibilities a step further. By extending `InnerModalProps<T>` and using a generic `T`, you harness the power of type inference, effectively enabling your modals to guarantee the type of data they resolve with.


## How EasyModal Works

EasyModal consists of several hooks and components that work together to bring this functionality into your React apps:

- `useModal` hook to access modal-related actions and state within your component.
- `show`, `update`, `hide`, and `remove` functions to control modals from anywhere in your code.
- `create` function to generate a High Order Component (HOC) for your modal components.

With EasyModal, showing a modal becomes as simple as calling `show()` with your modal component and potential props. The `show()` function returns a promise that resolves or rejects based on the user's interaction with the modal.

## Getting Started with EasyModal

To integrate EasyModal into your React application, start by wrapping your app with the `EasyModal.Provider`. This sets up the context for managing the modals:

```jsx
import { EasyModal } from 'ez-modal-react';

function App() {
  return (
    <EasyModal.Provider>
      {/* Your app components */}
    </EasyModal.Provider>
  );
}
```

### Real-World Type Inference with EasyModal

Let's dive into a realistic scenario illustrating the prowess of EasyModal's type inference system. Consider an interactive user form encapsulated in a modal dialog—a common need in today's applications.

```tsx
// Define your modal props and the type they resolve with.
interface Props extends InnerModalProps<string> {
  name: string;
  age: number;
}

// Create your modal with EasyModal.
export const UserInfoModal = EasyModal.create((props: Props) => {
  const modal = useModal<Props>();
  const [remark, setRemark] = useState('');

  // A handling function that simulates data processing and hides the modal.
  const handleSave = async () => {
    try {
      const val = await new Promise((resolve) => {
        setTimeout(() => {
          resolve('Data processed: ' + remark);
        }, 1000);
      });

      // Close the modal and pass resolved data back. The type is guaranteed!
      modal.hide(remark);
      console.log('Operation successful: ' + val);
    } catch (error) {
      // Error handling...
    }
  };

  // The rendered modal component with all its interactions.
  return (
    <Modal title="User Information" open={modal.visible} onOk={() => handleSave()} onCancel={() => modal.hide(null)}>
      Name: {props.name}!
      <div>
        Remark:
        <Input value={remark} onChange={(e) => setRemark(e.target.value)} />
      </div>
    </Modal>
  );
});
```

Here's how you would open this modal and use the type-inferred value upon closure:

```tsx
<Button
  onClick={async () => {
    // Open the UserInfoModal, passing props, and await the result.
    const userRemark = await EasyModal.show(UserInfoModal, { name: 'happy', age: 19 });

    // userRemark is assured to be a string due to the inferred type.
    console.log('User remark:', userRemark);
  }}
>
  GetUserRemark
</Button>
```

### Advantages of Using EasyModal

With EasyModal, you gain:

- **Simplified State Management:** Manage your modal logic cleanly through promises without messy state variables scattered across components.
- **Type Safety:** By extending `InnerModalProps<T>` and passing generics, you ensure that the data resolved is of the expected type, thus preventing a whole class of type-related bugs.
- **Effortless Updates:** Invoke `EasyModal.update` to refresh modal props dynamically, with type-checking ensuring you're setting props compatible with the modal's expectation.
- **Reusability and Modularity:** Create and reuse modals throughout your application, with complex logic nicely encapsulated and type-checked.

### Beyond Simple Alerts: Empower Complex Modals

While the traditional use-case for modals includes alerts, confirmations, or simple data entry, EasyModal empowers you to handle complex scenarios. Think of multi-step user onboarding, dynamic forms with real-time validation, or complex selection dialogs with asynchronously fetched data—all maintained with the flow and grace of promise-based logic and the precision of TypeScript typing.

### Conclusion

EasyModal offers an inspired blend of promise-based modality and robust type inference, creating an environment where React development is not only about components and state management but also about promises and flow control, all the while securely typed with TypeScript.

For developers aiming to elevate their UI dialogs to be more intuitive and maintainable, EasyModal is the tool to weave into the fabric of your React application. It's a testament to the power of contemporary React development—an art and science of creating user experiences that are both a joy to develop and to use.

So why not leverage the full potential of promises and types for your modals? Embrace EasyModal and transform the way you interact with your users—one promise at a time.

link:
https://github.com/raotaohub/ez-modal-react
⭐️~