How to read a referenced entry
This guide shows you how to read the content that a Reference field points at. You need a component that renders a step first. See How to render a step form.
A Reference field holds a pointer, and not the content. The entry travels beside the content of the step, so you resolve the pointer against the content of the client.
1. Resolve a single reference
Pass the raw field value to useReference() in React, or to getReference() in Svelte.
import { useReference, useStepContent, useStoreGlobal } from '@picked/react/hooks'
export function ProductCategory() {
const content = useStepContent()
const category = useStoreGlobal(useReference(content?.category))
if (!category) return null
return <span>{String(category.data.name ?? '')}</span>
}<script lang="ts">
import { getStepContent, getReference } from '@picked/svelte/hooks'
const content = getStepContent()
const category = getReference(content.map((c) => c?.category ?? null, { skipVoid: false }))
</script>
{#if $category}
<span>{$category.data.name ?? ''}</span>
{/if}In Svelte, pass a store and not a plain value. Content arrives after the component starts. A plain value therefore holds the result at "not set".
2. Resolve a repeatable reference
Use useReferences() or getReferences(). They give a list in field order.
import { useReferences, useStepContent, useStoreGlobal } from '@picked/react/hooks'
export function ProductCategories() {
const content = useStepContent()
const categories = useStoreGlobal(useReferences(content?.categories))
return (
<ul>
{categories.map((category) => (
<li key={category.id}>{String(category.data.name ?? '')}</li>
))}
</ul>
)
}<script lang="ts">
import { getStepContent, getReferences } from '@picked/svelte/hooks'
const content = getStepContent()
const categories = getReferences(content.map((c) => c?.categories ?? null, { skipVoid: false }))
</script>
<ul>
{#each $categories as category (category.id)}
<li>{category.data.name ?? ''}</li>
{/each}
</ul>The list holds no empty places, so you need no check for each item.
Handle a target that does not resolve
A single reference gives an empty result when Picked cannot resolve the target. A repeatable reference leaves the item out of the list.
This happens when somebody deleted the target, when the target belongs to another workspace, or when the chain of references is deeper than the limit.
Render something else for the empty case, as the React example above does.
Related
- Content — every hook and its return type.
- About content references — why the entry travels separately.
- How to point one entry at another — the dashboard side.
