import { Link } from '@brillout/docpress' import { UiFrameworkVikeExtension } from '../../components'
Environment: server, client.
Implemented by: (or yourself).
The useData()
component hook allows you to access the data that is returned by a data()
hook.
// SomeComponent.js
// Environment: server, client
import { useData } from 'vike-react/useData'
/* Or:
import { useData } from 'vike-vue/useData'
import { useData } from 'vike-solid/useData'
*/
// Inside a UI component
const data = useData()
const { name, price } = data
// /pages/product/@id/+data.js
// Environment: server
export { data }
async function data(pageContext) {
let product = await Product.findById(pagContext.routeParams.id)
// `product` is serialized and passed to the client. Therefore, we pick only the
// data the client needs in order to minimize what is sent over the network.
product = { name: product.name, price: product.price }
return product
}
See for more information about data fetching.
See .
// /pages/product/SomeComponent.ts
// Environment: server, client
import type { Data } from './+data'
// Inside a UI component
const data = useData<Data>()
// /pages/product/+data.ts
// Environment: server
export { data }
export type Data = Awaited<ReturnType<typeof data>>
import type { PageContextServer } from 'vike/types'
async function data(pageContext: PageContextServer) {
// ...
}
Using type inference as shown above is usually what you want, but if you want to enforce a type instead:
// +data.ts
export { data }
export type { Data }
type Data = /* the type you want to enforce */
import type { DataAsync } from 'vike/types'
const data: DataAsync = async (pageContext): Promise<Data> => {
// ...
}
In case you don't use a , you can implement useData()
yourself.
In general, for improved DX, we recommend using a
useData()
implementation. But you don't have to as shown at .
Examples:
- (React + JavaScript)
- (React + TypeScript)
- (Vue + JavaScript)
- (Vue + TypeScript)
vike-react
> /hooks/useData.tsxvike-vue
> /hooks/useData.tsvike-solid
> /hooks/useData.tsx