Skip to content

Commit

Permalink
feat (docs): separate stop handler from loading state (#4181)
Browse files Browse the repository at this point in the history
Co-authored-by: Lars Grammel <[email protected]>
  • Loading branch information
dragos-cojocaru and lgrammel authored Jan 2, 2025
1 parent 0f19645 commit 28387d9
Showing 1 changed file with 41 additions and 11 deletions.
52 changes: 41 additions & 11 deletions content/docs/04-ai-sdk-ui/08-object-generation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,9 @@ export async function POST(req: Request) {
### Loading State

The `isLoading` state returned by the `useObject` hook can be used for several
purposes
purposes:

- To show a loading spinner while the object is generated.
- To show a "Stop" button to abort the current message.
- To disable the submit button.

```tsx filename='app/page.tsx' highlight="6,13-20,24"
Expand All @@ -114,21 +113,14 @@ purposes
import { useObject } from 'ai/react';

export default function Page() {
const { isLoading, stop, object, submit } = useObject({
const { isLoading, object, submit } = useObject({
api: '/api/notifications',
schema: notificationSchema,
});

return (
<>
{isLoading && (
<div>
<Spinner />
<button type="button" onClick={() => stop()}>
Stop
</button>
</div>
)}
{isLoading && <Spinner />}

<button
onClick={() => submit('Messages during finals week.')}
Expand All @@ -148,6 +140,44 @@ export default function Page() {
}
```

### Stop Handler

The `stop` function can be used to stop the object generation process. This can be useful if the user wants to cancel the request or if the server is taking too long to respond.

```tsx filename='app/page.tsx' highlight="6,14-16"
'use client';

import { useObject } from 'ai/react';

export default function Page() {
const { isLoading, stop, object, submit } = useObject({
api: '/api/notifications',
schema: notificationSchema,
});

return (
<>
{isLoading && (
<button type="button" onClick={() => stop()}>
Stop
</button>
)}

<button onClick={() => submit('Messages during finals week.')}>
Generate notifications
</button>

{object?.notifications?.map((notification, index) => (
<div key={index}>
<p>{notification?.name}</p>
<p>{notification?.message}</p>
</div>
))}
</>
);
}
```

### Error State

Similarly, the `error` state reflects the error object thrown during the fetch request.
Expand Down

0 comments on commit 28387d9

Please sign in to comment.