Skip to main content

Object Generation

useObject is an experimental feature and only available in React, Svelte, and Vue.
The useObject hook allows you to create interfaces that represent a structured JSON object that is being streamed. In this guide, you will learn how to use the useObject hook in your application to generate UIs for structured data on the fly.

Example

The example shows a small notifications demo app that generates fake notifications in real-time.

Schema

It is helpful to set up the schema in a separate file that is imported on both the client and server.

Client

The client uses useObject to stream the object generation process. The results are partial and are displayed as they are received. Please note the code for handling undefined values in the JSX.

Server

On the server, we use streamText with Output.object() to stream the object generation process.

Enum Output Mode

When you need to classify or categorize input into predefined options, you can use the enum output mode with useObject. This requires a specific schema structure where the object has enum as a key with z.enum containing your possible values.

Example: Text Classification

This example shows how to build a simple text classifier that categorizes statements as true or false.

Client

When using useObject with enum output mode, your schema must be an object with enum as the key:

Server

On the server, use streamText with Output.choice() to stream the classification result:

Customized UI

useObject also provides ways to show loading and error states:

Loading State

The isLoading state returned by the useObject hook can be used for several purposes:
  • To show a loading spinner while the object is generated.
  • To disable the submit button.

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.

Error State

Similarly, the error state reflects the error object thrown during the fetch request. It can be used to display an error message, or to disable the submit button:
We recommend showing a generic error message to the user, such as “Something went wrong.” This is a good practice to avoid leaking information from the server.

Event Callbacks

useObject provides optional event callbacks that you can use to handle life-cycle events.
  • onFinish: Called when the object generation is completed.
  • onError: Called when an error occurs during the fetch request.
These callbacks can be used to trigger additional actions, such as logging, analytics, or custom UI updates.

Configure Request Options

You can configure the API endpoint, optional headers and credentials using the api, headers and credentials settings.