Skip to content

Validation Plugin: No rules reset possible?  #417

@skeadr

Description

@skeadr

Hello.

I'm facing issues with the following use case.

A configuration editor component for JSON data for different products.

  • It displays a form that is backed by a hookstate with the validation plugin
  • Displayed fields are dynamically displayed depending on the data. E.G. number fields get a number validation
  • json for the data is an argument for the editor

Product A has $.daysToDelivery
Product B has $.daysSinceLastAccident

If I switch between those to products and state.set(newData), and afterwards do state.valid(), I get the error for the other product, because the property is missing -> not a number.

I didn't find any way to "reset" the plugin that reruns the onCreate and resets the rules map.
I tried to hookstate(newData, validation()) for the global variable of the state, but get the HOOKSTATE-111

Working example of the problem

function Test() {
    const [data, setData] = useState<object>({})
    return (
        <div>
            <button onClick={() => setData({ daysToDelivery: 2 })}>Product A</button>
            <button onClick={() => setData({ daysSinceLastAccident: 3 })}>Product B</button>
            <TestEditor data={data} />
        </div>
    )
}

export let globalState = hookstate<any, Validation>({}, validation())
function TestEditor(props: { data: object }) {
    const { data } = props
    const state = useHookstate(globalState)

    useEffect(() => {
        //globalState = hookstate<any, Validation>(data, validation())
        state.set(data)
    }, [data])

    return (
        <>
            <br />
            {state.errors().map((error) => `${error.path}: ${error.message}`)}
            <br />
            <br />
            {Object.keys(state.get({ noproxy: true })).map((key) => (
                <TestNumberField propName={key} number={state.nested(key)} />
            ))}
        </>
    )
}

function TestNumberField(props: { propName: string; number: State<any, Validation> }) {
    const valueState = useHookstate(props.number)

    valueState.validate((value) => {
        const number = Number(value)
        if (isNaN(number)) return false
        return Number.isInteger(number)
    }, "not a number")

    return (
        <>
            {props.propName}
            <br />
            <input value={valueState.get()} onChange={(e) => valueState.set(e.target.value)} />
        </>
    )
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions