The defer function wraps a promise with a deferred state object that can be used to inspect the promise's state. This deferred promise can then be passed to the useAwaited hook or the <Await> component for suspending until the promise is resolved or rejected.
The defer function accepts a single argument, the promise to wrap with a deferred state object.
import { defer } from '@tanstack/react-router'
const route = createRoute({
loader: () => {
const deferredPromise = defer(fetch('/api/data'))
return { deferredPromise }
},
component: MyComponent,
})
function MyComponent() {
const { deferredPromise } = Route.useLoaderData()
const data = useAwaited({ promise: deferredPromise })
// or
return (
<Await promise={deferredPromise}>
{(data) => <div>{JSON.stringify(data)}</div>}
</Await>
)
}
import { defer } from '@tanstack/react-router'
const route = createRoute({
loader: () => {
const deferredPromise = defer(fetch('/api/data'))
return { deferredPromise }
},
component: MyComponent,
})
function MyComponent() {
const { deferredPromise } = Route.useLoaderData()
const data = useAwaited({ promise: deferredPromise })
// or
return (
<Await promise={deferredPromise}>
{(data) => <div>{JSON.stringify(data)}</div>}
</Await>
)
}
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.