保留一个值到下次访问,跟踪变化,并在服务器上读取 cookie。
用存储辅助函数保存一个值,稍后再读回来。它们支持 localStorage、sessionStorage 和 cookie,还能让你监听变化。
对于用户偏好,比如主题或侧边栏状态,把一个存储传给 createPreference。
选择存储
按值的保留时长和服务器是否需要读取它来选择:
| 存储 | 保留时长 | 共享对象 | 服务器可读取 |
|---|---|---|---|
createLocalStorage | 直到被移除 | 站点上的其他标签页 | 否 |
createSessionStorage | 标签页打开期间 | 当前标签页 | 否 |
createCookieStorage | 一年,或 maxAge 指定的秒数 | 请求和其他标签页 | 是 |
想留到下次访问的笔记可以用 localStorage。临时的草稿可以用 sessionStorage。会影响服务端渲染内容的偏好可以用 cookie。
保存一个值
这些辅助函数按名称存储字符串,这个名称会成为 localStorage 或 sessionStorage 的键,或者 cookie 的名字:
import { createLocalStorage } from "@ui-sdk/core"
const note = createLocalStorage("note")
note.set("Buy milk")
note.get()
note.remove()
note.get()第一次 get() 返回 "Buy milk"。调用 remove() 之后,它返回 null。
import * as React from "react"
import {
createCookieStorage,
createLocalStorage,
createSessionStorage,
type ValueStorage,
} from "@ui-sdk/core"
import {
Field,
FieldControl,
FieldDescription,
FieldLabel,
} from "@ui-sdk/react/field"
import {
SegmentedControl,
SegmentedControlIndicator,
SegmentedControlItem,
} from "@ui-sdk/react/segmented-control"
const storages: { label: string; storage: ValueStorage; lasts: string }[] = [
{
label: "localStorage",
storage: createLocalStorage("ui-sdk-note"),
lasts: "Stays until cleared, in every tab.",
},
{
label: "sessionStorage",
storage: createSessionStorage("ui-sdk-note"),
lasts: "Stays while this tab is open.",
},
{
label: "Cookie",
storage: createCookieStorage("ui-sdk-note"),
lasts: "Stays a year, and the server reads it too.",
},
]
const noServerValue = () => null
function Example() {
const [picked, setPicked] = React.useState("localStorage")
const { storage, lasts } = storages.find(({ label }) => label === picked)!
const note = React.useSyncExternalStore(
storage.subscribe,
storage.get,
noServerValue
)
const [available, setAvailable] = React.useState(true)
React.useEffect(() => setAvailable(storage.available()), [storage])
return (
<div data-slot="stack">
<div data-slot="controls">
<SegmentedControl
aria-label="Keep the note in"
value={picked}
onValueChange={(next) => next && setPicked(next)}
>
<SegmentedControlIndicator />
{storages.map(({ label }) => (
<SegmentedControlItem key={label} value={label}>
{label}
</SegmentedControlItem>
))}
</SegmentedControl>
</div>
<div data-slot="stack">
<Field disabled={!available}>
<FieldLabel>Note</FieldLabel>
<FieldControl
value={note ?? ""}
onChange={(event) => storage.set(event.target.value)}
placeholder={
available ? "Type, then reload the page" : "Unavailable here"
}
/>
<FieldDescription>
{available ? lasts : "This browser blocks it here."}
</FieldDescription>
</Field>
<button
type="button"
onClick={() => storage.remove()}
disabled={note === null}
>
Clear Note
</button>
</div>
</div>
)
}
export { Example }存储不可用时
浏览器可能禁止存储,或者存储空间会用完。如果读取失败,get() 返回 null。对 localStorage 和 sessionStorage 来说,写入成功时 set 和 remove 返回 true,失败时返回 false。
用 available() 做初始检查。之后的写入仍可能失败,所以也要检查它的返回值:
if (!note.available()) {
console.log("Saving is unavailable here.")
}
if (!note.set("Buy milk")) {
console.log("The note wasn't saved.")
}存储已满时,你仍然可以读取或移除已有的值。
对 cookie 来说,true 表示没有报告错误,并不能确认 cookie 已经保存或移除。
在服务器上,localStorage 和 sessionStorage 不可用。要在那里读取保存的值,请使用 cookie。
跟踪变化
先用 get 读取初始值,再订阅变化。subscribe 不会用初始值调用你的监听器:
function logNote(value: string | null) {
console.log(value ?? "")
}
logNote(note.get())
const stop = note.subscribe(logNote)通过种类和 ID 相同的存储写入时,页面上的监听器会收到通知,包括通过 note 本身的写入。localStorage 还会跟踪其他标签页的变化。在支持 cookieStore 的浏览器里,cookie 也会跟踪其他标签页。
不再需要订阅时调用返回的函数,比如组件卸载时:
stop()在服务器上读取 cookie
在服务端渲染期间,传入请求的 Cookie 头来读取保存的值:
import { createCookieStorage } from "@ui-sdk/core"
function readDensity(request: Request) {
const density = createCookieStorage("density", {
cookie: request.headers.get("cookie"),
})
return density.get()
}像上面那样在请求处理函数里创建存储,让每个访客的 cookie 保持独立。在浏览器里,它读取 document.cookie。
在服务器上,提供 Cookie 头时 available() 返回 true,但 set 和 remove 返回 false。这个辅助函数读取请求的 cookie,不设置响应头。它的 readsOnServer 标记让 createPreference 这类辅助函数能在初始状态里使用保存的值。
默认情况下,cookie 保留一年,使用路径 / 和 SameSite=Lax,在 HTTPS 页面上使用 Secure。你可以用 maxAge、path、domain、sameSite 和 secure 修改这些设置。
在水合前显示值
服务器无法读取 localStorage 或 sessionStorage。对于依赖保存值的样式,script 会生成一段 JavaScript,在水合之前把值放到 data-* 属性上:
import { createLocalStorage } from "@ui-sdk/core"
const densityStorage = createLocalStorage("density")
const script = densityStorage.script({
attribute: "data-density",
values: ["comfortable", "compact"],
})渲染元素时带上它的默认属性,比如 data-density="comfortable"。紧跟在这个元素之后,把 script 渲染成内联 JavaScript。它会在页面加载时读取保存的值,并更新前一个元素的属性。
只有列在 values 里的值才会被写入。保存的值缺失或无效时,属性保持服务器渲染的样子。属性名必须以 data- 开头。
脚本只更新属性。组件挂载时读取存储,并订阅变化,让它的状态保持最新。当你在自己的框架里渲染这段脚本时,要考虑到属性会在水合之前发生变化。
种类和 ID 相同的脚本共享一次初始读取。cookie 存储的 script 返回 undefined,因为服务器自己就能渲染 cookie 的值。
对于用户偏好,用 Preferences 应用它们,这样只需渲染一段脚本,就能让它们的属性保持最新。
API 参考
idstring- The ID the value is kept under: the localStorage or sessionStorage key, or the cookie's name.
- 示例: Keep a Value
readsOnServerboolean- Whether the server reads the value too, so it renders right from the first render. True for cookies.
- 示例: Read a Cookie on the Server
script(options: StorageScriptOptions) => string- The inline script a component renders right after its root, which puts the saved value on the root before hydration, so CSS shows it on the first paint. Undefined for a cookie, since the server renders its value.
- 示例: Show a Value Before Hydration
available() => boolean- Whether storage appears available. A later write can still fail. On the server, a cookie with a request header is available for reading only.
- 示例: When Storage Is Unavailable
get() => string | null- The value kept under the ID, or null when nothing is, or the storage is unavailable.
- 示例: Keep a Value
set(value: string) => boolean- Saves a value under the ID. Returns false when writing is unavailable or the browser reports a write failure. For cookies, true means the assignment didn't throw; it doesn't confirm the cookie was saved.
- 示例: Keep a Value
remove() => boolean- Removes the value. Returns false when writing is unavailable or the browser reports a write failure. For cookies, true means the assignment didn't throw; it doesn't confirm the cookie was removed.
- 示例: Keep a Value
subscribe(listener: (value: string | null) => void) => () => void- Hears the value change, through another storage with the same ID on the page or in another tab. Returns the function that stops it.
- 示例: Follow Changes
cookie?string | null- The request's
Cookieheader, so the server reads the same value the browser will. - 示例: Read a Cookie on the Server
domain?string- The domain that sends the cookie. Defaults to the page's host.
- 示例: Read a Cookie on the Server
sameSite?"lax" | "none" | "strict"- Whether other sites' requests send the cookie.
- 示例: Read a Cookie on the Server
secure?boolean- Whether only HTTPS requests send the cookie. Defaults to true on HTTPS pages.
- 示例: Read a Cookie on the Server
attribute`data-${string}`- The attribute that shows the value, which has to start with
data-, like"data-color-scheme". - 示例: Show a Value Before Hydration
valuesreadonly string[]- The values it may show. Anything else saved under the ID leaves the root as the server rendered it.
- 示例: Show a Value Before Hydration