AI SDK UIuseObject

experimental_useObject()

useObject is an experimental feature and only available in React.

Allows you to consume text streams that represent a JSON object and parse them into a complete object based on a Zod schema. You can use it together with streamObject in the backend.

'use client';
import { experimental_useObject as useObject } from 'ai/react';
export default function Page() {
const { object, submit } = useObject({
api: '/api/use-object',
schema: z.object({ content: z.string() }),
});
return (
<div>
<button onClick={() => submit('example input')}>Generate</button>
{object?.content && <p>{object.content}</p>}
</div>
);
}

Import

import { experimental_useObject as useObject } from 'ai/react'

API Signature

Parameters

api:

string
The API endpoint. It should stream JSON that matches the schema as chunked text.

schema:

ZodSchema<RESULT>
A Zod schema that defines the shape of the complete object.

id?:

string
Allows you to consume text streams that represent a JSON object and parse them into a complete object based on a Zod schema.

initialValue?:

DeepPartial<RESULT> | undefined
An optional value for the initial object.

fetch:

FetchFunction
Optional. A custom fetch function to be used for the API call. Defaults to the global fetch function.

Returns

submit:

(input: INPUT) => void
Calls the API with the provided input as JSON body.

object:

DeepPartial<RESULT> | undefined
The current value for the generated object. Updated as the API streams JSON chunks.

error:

undefined | unknown
The error object if the API call fails.

isLoading:

boolean
Boolean flag indicating whether a request is currently in progress.

stop:

() => void
Function to abort the current API request.

Examples