experimental_useObject()
useObject is an experimental feature and only available in React, Svelte,
and Vue.
Allows you to consume text streams that represent a JSON object and parse them into a complete object based on a schema.
You can use it together with streamObject in the backend.
'use client';
import { experimental_useObject as useObject } from '@ai-sdk/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
API Signature
Parameters
<PropertiesTable
content={[
{
name: 'api',
type: 'string',
description:
'The API endpoint that is called to generate objects. It should stream JSON that matches the schema as chunked text. It can be a relative path (starting with /) or an absolute URL.',
},
{
name: 'schema',
type: 'Zod Schema | JSON Schema',
description:
'A schema that defines the shape of the complete object. You can either pass in a Zod schema or a JSON schema (using the jsonSchema function).',
},
{
name: 'id?',
type: 'string',
description:
'A unique identifier. If not provided, a random one will be generated. When provided, the useObject hook with the same id will have shared states across components.',
},
{
name: 'initialValue',
type: 'DeepPartial
Returns
<PropertiesTable
content={[
{
name: 'submit',
type: '(input: INPUT) => void',
description: 'Calls the API with the provided input as JSON body.',
},
{
name: 'object',
type: 'DeepPartial
Examples
<ExampleLinks examples={[ { title: 'Streaming Object Generation with useObject', link: '/examples/next-pages/basics/streaming-object-generation', }, ]} />