42-px / effector-forms

106 stars 16 forks source link

setInitialForm should reinit form #31

Open notmedia opened 6 months ago

notmedia commented 6 months ago

In case when you have to "recreate" form as new.

test("setInitialForm", () => {
    const form = createForm({
        fields: {
            email: {
                init: "",
                rules: [
                    rules.email(),
                ],
            },
            password: {
                init: "",
                rules: [
                    rules.required()
                ],
            },
        },
        validateOn: ["submit"],
    })

    // Retrieve data from backend
    form.setInitialForm({
        email: "default@example.com",
    })

    // User changed password
    form.fields.password.onChange("mypassword")

    // Save and retrieve data from backend
    form.setInitialForm({
        email: "default@example.com",
        password: "mypassword"
    })
    form.reset();

    expect(form.fields.email.$value.getState()).toBe("default@example.com")
    expect(form.fields.password.$value.getState()).toBe("mypassword")

    // Same form used for another item (imagine that you are editing a collection)
    // Retrieve data from backend
    form.setInitialForm({
        email: "test@example.com",
    })
    form.reset();

    expect(form.fields.email.$value.getState()).toBe("test@example.com")
    // Here the password is "mypassword", expects to be an empty string
    expect(form.fields.password.$value.getState()).toBe("")
})
pijng commented 6 months ago

Seems like changing setInitialForm to setForm will do the trick. But I'm still not sure if that's the expected behavior.

notmedia commented 6 months ago

Seems like changing setInitialForm to setForm will do the trick. But I'm still not sure if that's the expected behavior.

No. setForm method doesn't set the initial form state and resetting the form in this case would be broken.