@k8ordo/state

Migration

Keep reading the values an older schema saved after the shape changes. version and migrate turn an old value into the current shape.

On this page

Without version

json
{"layout":"list","pageSize":50}
Saved by the previous schema `{ layout, pageSize }`
{"view":"grid","pageSize":50}
Read by the current schema `{ view, pageSize }`: `layout` is never read, and `view` starts from its default. Not written back

Without version, the saved value is the bare values object. A value an older schema saved is read field by field, like any other input: every field the current schema accepts keeps its value, and the rest fall back to their defaults.

  • A field was added: it starts from its default, and the other values stay.
  • A constraint was tightened: only the values that no longer fit fall back to their defaults.
  • A field was renamed: the value under the old name is never read, and the new field starts from its default. layout and view above are this case.
  • A value changed meaning: the old value is read with the new meaning, or falls back to its default when it no longer fits.

The first two work as they are. The last two raise no error: the value is lost or read with another meaning. version and migrate convert them into the current shape.

version and migrate

prefs.ts
export const prefs = defineLocalState(
  'prefs',
  z.object({
    view: z.enum(['grid', 'table']).default('grid'),
    pageSize: z.number().default(20),
  }),
  {
    version: 1,
    migrate: (old) => ({
      view: old['layout'] === 'list' ? 'table' : 'grid',
      pageSize: old['pageSize'],
    }),
  },
);

defineLocalState and defineCookieState take version and migrate as their third argument. Here the values saved before the version existed had the shape { layout: 'list' | 'cards' }, and migrate turns that layout into the current view.

A versioned value is saved as [version, values], and a value with no version reads as version 0. Declaring version: 1 when the shape first changes migrates the existing values from 0.

localStorage: k8ordo-state:prefs
{"layout":"list","pageSize":50}
Saved before the version existed
[1,{"view":"table","pageSize":50}]
Migrated and written back

version is a positive integer. Anything else fails as the definition is created, with an error like "prefs" version must be a positive integer, got 0.

Reading an older value

A value older than version is read in three steps.

  1. migrate(old, fromVersion) turns the old values into the current shape. fromVersion is the version the value was saved with.
  2. What it returns passes the schema field by field, like any read.
  3. The browser store writes the result back in the current version.

migrate returns an object with the schema’s keys; another key is a type error. Hand old values over as they are.

On the server, parseCookies migrates too, but never writes back: a page cannot answer with Set-Cookie. The browser writes back after hydration. Both read the same values, so the display does not change at hydration.

The next change

prefs.ts
export const prefs = defineLocalState(
  'prefs',
  z.object({
    view: z.enum(['grid', 'table']).default('grid'),
    perPage: z.number().default(20),
  }),
  {
    version: 2,
    migrate: (old, fromVersion) => {
      if (fromVersion === 0) {
        return {
          view: old['layout'] === 'list' ? 'table' : 'grid',
          perPage: old['pageSize'],
        };
      }
      return { view: old['view'], perPage: old['pageSize'] };
    },
  },
);

On the next change, raise the version and branch on migrate’s second argument, fromVersion. Here version 2 renames pageSize to perPage. Values from version 0 and version 1 both reach the current shape in one migrate.

Other versions and errors

A few more things come with version.

  • A newer value: one saved by a tab that loaded the next deploy first. It is read field by field without migrate and never written back, so the newer tab’s value stays.
  • An error inside migrate: it reads as nothing saved, with the defaults, and the saved value is left as it was. Fix migrate, and the next load migrates it.
  • Just after adopting a version: the saved shape changes to [version, values]. A tab still running the code from before reads it as nothing saved until it reloads.
  • inlineRead(): it returns only the current version. A value of any other version is null until a store has migrated it. See Before hydration.
  • defineSessionState: it takes no version. Its saved values are discarded with the tab. Only a tab kept open across a deploy holds an older shape, so reading field by field is enough.
k8ordo

React libraries that use Baseline features without holding back.