Object Generation
useObject is an experimental feature and only available in React, Svelte,
and Vue.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 usesuseObject 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 usestreamText 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 theenum 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 usinguseObject with enum output mode, your schema must be an object with enum as the key:
Server
On the server, usestreamText with Output.choice() to stream the classification result:
Customized UI
useObject also provides ways to show loading and error states:
Loading State
TheisLoading 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
Thestop 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, theerror 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.
Configure Request Options
You can configure the API endpoint, optional headers and credentials using theapi, headers and credentials settings.