UNPKG

mobx-react-routing

Version:
55 lines (54 loc) 1.69 kB
import { action, computed, makeObservable } from 'mobx'; import { queryParamsPresets } from './query-params-presets.js'; export class QueryParamsField { config; name; constructor(config) { this.config = config; this.name = this.config.name; computed(this, 'rawValue'); computed(this, 'value'); action(this, 'set'); makeObservable(this); } get rawValue() { return this.config.queryParams.data[this.name]; } get value() { return this.config.deserialize(this.rawValue) ?? this.config.defaultValue; } set = async (value) => { if (value === this.value) { return; } const serializedValue = this.config.serialize(value); await this.config.queryParams.update({ [this.name]: serializedValue, }, this.config.strategy !== 'push'); }; createUrl = (value) => { const serializedValue = this.config.serialize(value ?? this.value); return this.config.queryParams.buildUrl({ [this.name]: serializedValue, }); }; /** * Create get\set value, which is synchronized with the query parameter * Create by preset */ static createWithPreset(config) { const { serialize, deserialize } = queryParamsPresets[config.preset]; return new QueryParamsField({ ...config, serialize, deserialize, }); } /** * Create get\set value, which is synchronized with the query parameter * Manual handling of the query parameter */ static create(config) { return new QueryParamsField(config); } }