try-error Documentation

React Hooks

Powerful hooks for integrating try-error with React components

useTryAsync

useTryAsync Hook Signaturetypescript
function useTryAsync<T>(
  asyncFn: () => Promise<T>,
  deps?: React.DependencyList
): {
  data: T | null;
  error: TryError | null;
  loading: boolean;
  refetch: () => void;
}

Hook for handling asynchronous operations with automatic loading states and error handling.

Example

useTryAsync Exampletsx
1import { useTryAsync } from '@try-error/react';
2
3function UserProfile({ userId }: { userId: string }) {
4  const { data: user, error, loading, refetch } = useTryAsync(
5    async () => {
6      const response = await fetch(`/api/users/${userId}`);
7      if (!response.ok) throw new Error('Failed to fetch user');
8      return response.json();
9    },
10    [userId]
11  );
12
13  if (loading) {
14    return <div className="animate-pulse">Loading user...</div>;
15  }
16
17  if (error) {
18    return (
19      <div className="text-red-600">
20        <p>Error: {error.message}</p>
21        <button onClick={refetch} className="mt-2 px-4 py-2 bg-blue-500 text-white rounded">
22          Retry
23        </button>
24      </div>
25    );
26  }
27
28  if (!user) {
29    return <div>No user found</div>;
30  }
31
32  return (
33    <div>
34      <h1>{user.name}</h1>
35      <p>{user.email}</p>
36      <button onClick={refetch}>Refresh</button>
37    </div>
38  );
39}

Parameters

  • asyncFn - The async function to execute
  • deps - Dependency array (optional)

useTrySync

useTrySync Hook Signaturetypescript
function useTrySync<T>(
  syncFn: () => T,
  deps?: React.DependencyList
): {
  data: T | null;
  error: TryError | null;
  execute: () => void;
}

Hook for handling synchronous operations that might throw errors.

Example

useTrySync Exampletsx
1import { useTrySync } from '@try-error/react';
2
3function ConfigDisplay({ configString }: { configString: string }) {
4  const { data: config, error, execute } = useTrySync(
5    () => JSON.parse(configString),
6    [configString]
7  );
8
9  if (error) {
10    return (
11      <div className="text-red-600">
12        <p>Invalid JSON: {error.message}</p>
13        <button onClick={execute}>Try Again</button>
14      </div>
15    );
16  }
17
18  return (
19    <pre className="bg-gray-100 p-4 rounded">
20      {JSON.stringify(config, null, 2)}
21    </pre>
22  );
23}

useTryMutation

useTryMutation Hook Signaturetypescript
function useTryMutation<T, TVariables = void>(
  mutationFn: (variables: TVariables) => Promise<T>
): {
  mutate: (variables: TVariables) => Promise<void>;
  data: T | null;
  error: TryError | null;
  loading: boolean;
  reset: () => void;
}

Hook for handling mutations (create, update, delete operations) with loading and error states.

Example

useTryMutation Exampletsx
1import { useTryMutation } from '@try-error/react';
2
3function CreateUserForm() {
4  const { mutate: createUser, loading, error, data } = useTryMutation(
5    async (userData: { name: string; email: string }) => {
6      const response = await fetch('/api/users', {
7        method: 'POST',
8        headers: { 'Content-Type': 'application/json' },
9        body: JSON.stringify(userData),
10      });
11      if (!response.ok) throw new Error('Failed to create user');
12      return response.json();
13    }
14  );
15
16  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
17    e.preventDefault();
18    const formData = new FormData(e.currentTarget);
19    await createUser({
20      name: formData.get('name') as string,
21      email: formData.get('email') as string,
22    });
23  };
24
25  if (data) {
26    return <div className="text-green-600">User created successfully!</div>;
27  }
28
29  return (
30    <form onSubmit={handleSubmit}>
31      <input name="name" placeholder="Name" required />
32      <input name="email" type="email" placeholder="Email" required />
33      <button type="submit" disabled={loading}>
34        {loading ? 'Creating...' : 'Create User'}
35      </button>
36      {error && <p className="text-red-600">Error: {error.message}</p>}
37    </form>
38  );
39}

useTryCallback

useTryCallback Hook Signaturetypescript
function useTryCallback<T extends (...args: any[]) => any>(
  callback: T,
  deps: React.DependencyList
): T & {
  error: TryError | null;
  clearError: () => void;
}

Hook that wraps a callback function with error handling, similar to useCallback but with try-error integration.

Example

useTryCallback Exampletsx
1import { useTryCallback } from '@try-error/react';
2
3function FileUploader() {
4  const handleFileUpload = useTryCallback(
5    async (file: File) => {
6      if (file.size > 10 * 1024 * 1024) {
7        throw new Error('File too large (max 10MB)');
8      }
9      
10      const formData = new FormData();
11      formData.append('file', file);
12      
13      const response = await fetch('/api/upload', {
14        method: 'POST',
15        body: formData,
16      });
17      
18      if (!response.ok) throw new Error('Upload failed');
19      return response.json();
20    },
21    []
22  );
23
24  return (
25    <div>
26      <input
27        type="file"
28        onChange={(e) => {
29          const file = e.target.files?.[0];
30          if (file) handleFileUpload(file);
31        }}
32      />
33      {handleFileUpload.error && (
34        <div className="text-red-600">
35          <p>Upload error: {handleFileUpload.error.message}</p>
36          <button onClick={handleFileUpload.clearError}>Clear Error</button>
37        </div>
38      )}
39    </div>
40  );
41}

Best Practices

✅ Do

  • • Use dependency arrays to control when effects re-run
  • • Handle loading states for better user experience
  • • Provide retry mechanisms for failed operations
  • • Use useTryMutation for state-changing operations
  • • Clear errors when appropriate

❌ Don't

  • • Forget to handle error states in your UI
  • • Use useTryAsync for mutations (use useTryMutation instead)
  • • Ignore loading states
  • • Create new functions on every render without memoization

Related Pages

React Components

Pre-built components for common patterns

View Components →

React Examples

Real-world usage examples

See Examples →