Guide
Dynamic keys
Handle keys that only exist at runtime, such as user-defined filters, with dynamicQueryState.
Sometimes the set of keys comes from data: the columns of a table, the fields of a saved view, filters a user configures. dynamicQueryState goes inside a useQueryStates schema and owns every key under one prefix.
/guide/dynamic-keys
department
remote
salary ≥
[]
Three runtime-defined fields, four possible URL keys, one typed array.
You describe four things:
definitions: the runtime definitions that exist right now.resolve: every URL key one definition may use, with its codec. One definition can use several keys, for example one per operator. The codec's rules apply; itsdefaultand write options are not used here.parse: the parsed URL entries to your value.serialize: your value back to URL entries. Keys it leaves out are removed from the URL.
interface FilterField {
key: string
codec: AnyQueryCodec operators: ('eq' | 'gte')[]
}
interface Rule {
field: string
operator: 'eq' | 'gte'
value: unknown
}
const fields: FilterField[] = [
{ key: 'department', codec: stringCodec(), operators: ['eq'] },
{ key: 'remote', codec: booleanCodec(), operators: ['eq'] },
{ key: 'salary', codec: numberCodec({ int: true, min: 0 }), operators: ['gte'] },
]
const urlKey = (field: string, operator: string) =>
operator === 'eq' ? field : `${field}~${operator}`
const state = useQueryStates({
prefix: 'f',
schema: {
rules: dynamicQueryState({
urlPrefix: 'fields',
definitions: () => fields,
resolve: (field) =>
field.operators.map((operator) => ({
urlKey: urlKey(field.key, operator),
codec: field.codec,
})),
parse: (entries): Rule[] =>
[...entries].map(([key, value]) => {
const [field = key, operator = 'eq'] = key.split('~')
return { field, operator: operator as Rule['operator'], value }
}),
serialize: (rules) =>
new Map(rules.map((rule) => [urlKey(rule.field, rule.operator), rule.value])),
default: [] as Rule[],
}),
},
})
// ?f.fields.department=Engineering&f.fields.salary~gte=60000
state.value.rules
How keys are built
A dynamic key is prefix.urlPrefix.urlKey, where prefix is the group's prefix (optional) and urlKey is what resolve returned. Above, salary with gte becomes f.fields.salary~gte.
Rules
definitionsis read when the group reads or writes. Return the definitions that exist at that moment.- Only keys that some definition resolves are read. Unknown keys under the prefix are ignored, so a stale link with a removed field is harmless.
- A value its codec rejects is left out of
entriesand reported inissues. - When no accepted key is present, the value is
default, andparseis not called. - A write first clears every resolved key, then sets the ones
serializereturned. To remove a definition, write the value without it before you remove the definition, so its keys are still known and get cleared. - Dynamic entries can sit next to static ones in the same schema, and everything is written in one navigation.