Search code examples
f#fable-f#elmish

Convert React.FormEvent to BodyInit using Fable-Elmish


I am trying to upload a file using Fable-Elmish and the React Helpers. However, I can't work out how to convert the form event when a file is selected into something that I can send off to the server using Fetch. This is the view:

R.input [
        ClassName "input-control" 
        Type "file"
        OnChange (fun x -> FileUploaded x.target |> dispatch )
    ] []

The corresponding part of my update function:

 | FileUploaded file ->
    model, Cmd.ofPromise postCsv file FetchSuccess FetchFailure

And the function to call the api with fetch:

let postData input =
    let formData = FormData.Create()
    formData.append("file.csv", input?files)
    let defaultProps =
        [ RequestProperties.Method HttpMethod.POST
        ; RequestProperties.Body (formData |> unbox)]
    promise {
        return! Fable.PowerPack.Fetch.fetch ("/api/data") defaultProps
    }

How can I can convert the React.FormEvent into the BodyInit that fetch needs?


Solution

  • It turns out I wasn't using the FileList API properly. Here's the working solution for the post method:

    let postData input =
    let formData = FormData.Create()
    formData.append("file.csv", input?files?item(0))
    let defaultProps =
        [ RequestProperties.Method HttpMethod.POST
        ;RequestProperties.Headers [unbox EncType "multipart/form-data"]
        ; RequestProperties.Body (formData |> unbox)]
    promise {
        return! Fable.PowerPack.Fetch.fetch ("/api/data") defaultProps
    }