thoth-org / Thoth.Elmish.FormBuilder

https://thoth-org.github.io/Thoth.Elmish.FormBuilder/
MIT License
10 stars 5 forks source link

FormBuilder and Thoth.Fetch don't work well together #10

Open MangelMaxime opened 4 years ago

MangelMaxime commented 4 years ago

Issue by rmunn Wednesday Aug 21, 2019 at 03:50 GMT Originally opened as https://github.com/MangelMaxime/Thoth/issues/163


Currently the only way to get data out of a form is toJson (see #93), which returns a JSON string like {"Name": "Robin", "Description": "xyz"}. When I pass that JSON to Thoth.Fetch (for example, with Cmd.OfPromise.perform (fun data -> Fetch.post(url, data)) json GotFormResult, Thoth.Fetch sees that I passed it a string, and helpfully JSON-encodes that string by backslash-escaping quotation marks, so that my API server receives: "{\"Name\": \"Robin\", \"Description\": \"xyz\"}". Then my server code complains that it received a string when it was expecting an object.

I see two ways of resolving this (well, three, but one is to not use Thoth.Fetch):

MangelMaxime commented 4 years ago

Comment by rmunn Wednesday Aug 21, 2019 at 04:41 GMT


I'm currently resolving this by doing:

let json = Form.toJson formConfig newFormState
let nextModel = { currentModel with FormState = newFormState }
match Thoth.Json.Decode.Auto.fromString<ApiSubmission> json with
| Ok data ->
    let url = "/api/path"
    nextModel, Cmd.OfPromise.perform (fun data -> Fetch.post(url, data)) data GotFormResult
| Error err ->
    // TODO: Report this to user in some form
    printfn "Decoding error: %s" err
    nextModel, Cmd.none

Which works reasonably well and allows me to type-check that the form is building a correct ApiSubmission record. But what I'd really like is to cut out the Thoth.Json middleman and extract the form data myself, assigning it to the fields of an ApiSubmission record before passing it on to Fetch.post, so that it only has to be JSON-encoded once. (The solution above does an encode in toJson, then a decode, then another encode in Fetch.post).

MangelMaxime commented 4 years ago

Comment by MangelMaxime Wednesday Aug 21, 2019 at 07:12 GMT


Hello, this is indeed a problem.

I am prototyping the next version of FormBuilder, which should solve several issues we have with the current version. It will make the user responsible to store the data (less of a black box as we have now). So you will have direct access to the type and not have to hack your way around toJson.