Skip to content

Commit 4ab883f

Browse files
authored
fix (ai/react): useObject error handling (#2877)
1 parent 40b4205 commit 4ab883f

File tree

4 files changed

+17
-4
lines changed

4 files changed

+17
-4
lines changed

‎.changeset/strong-nails-fold.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@ai-sdk/react': patch
3+
---
4+
5+
fix (ai/react): useObject error handling

‎examples/next-openai/app/use-object/page.tsx‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { experimental_useObject as useObject } from 'ai/react';
44
import { notificationSchema } from '../api/use-object/schema';
55

66
export default function Page() {
7-
const { submit, isLoading, object, stop } = useObject({
7+
const { submit, isLoading, object, stop, error } = useObject({
88
api: '/api/use-object',
99
schema: notificationSchema,
1010
});
@@ -21,6 +21,12 @@ export default function Page() {
2121
Generate notifications
2222
</button>
2323

24+
{error && (
25+
<div className="mt-4 text-red-500">
26+
An error occurred. {error.message}
27+
</div>
28+
)}
29+
2430
{isLoading && (
2531
<div className="mt-4 text-gray-500">
2632
<div>Loading...</div>

‎packages/react/src/use-object.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ export type Experimental_UseObjectHelpers<RESULT, INPUT> = {
8787
/**
8888
* The error object of the API request if any.
8989
*/
90-
error: undefined | unknown;
90+
error: Error | undefined;
9191

9292
/**
9393
* Flag that indicates whether an API request is in progress.
@@ -123,7 +123,7 @@ function useObject<RESULT, INPUT = any>({
123123
{ fallbackData: initialValue },
124124
);
125125

126-
const [error, setError] = useState<undefined | unknown>(undefined);
126+
const [error, setError] = useState<undefined | Error>(undefined);
127127
const [isLoading, setIsLoading] = useState(false);
128128

129129
// Abort controller to cancel the current API call.
@@ -212,7 +212,8 @@ function useObject<RESULT, INPUT = any>({
212212
onError(error);
213213
}
214214

215-
setError(error);
215+
setIsLoading(false);
216+
setError(error instanceof Error ? error : new Error(String(error)));
216217
}
217218
};
218219

‎packages/react/src/use-object.ui.test.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ describe('text stream', () => {
173173
await screen.findByTestId('error');
174174
expect(screen.getByTestId('error')).toHaveTextContent('Not found');
175175
expect(onErrorResult).toBeInstanceOf(Error);
176+
expect(screen.getByTestId('loading')).toHaveTextContent('false');
176177
},
177178
),
178179
);

0 commit comments

Comments
 (0)