Search code examples
f#fable-f#elmish

Elmish dispatch on Fable React stateful component


I need to use Fable-React stateful component with elmish dispatch. I can not figure out how to create it.

I am using this project template: https://github.com/fable-elmish/templates

here is model:

module Home.Types

    [<Pojo>]
    type Model = {
        isLoading:                  bool
    }

here is the component:

type Documentation(props) as this =
    inherit Component<Documentation.Types.Model,obj>(props)
    do
        ()

    override this.componentWillMount () =
        printfn "componentWillMount"
        **RequestProcessDocumentation |> dispatch <-- this is what I need**

    override this.render() =
        printfn "render"
        let (?) = Fable.Core.JsInterop.(?)

        div []
            [
                p [] [str(this.props.isLoading.ToString())]
                button [ OnClick (fun _ -> RequestProcessDocumentation |> dispatch ) ] [str("Click me")]
            ]

how can I create it using ofType function, so then I can use it like this:

  let pageHtml =
    function
    | Home -> Home.View.root model.home (HomeMsg >> dispatch)
    | Documentation -> documentation (DocumentationMsg >>  

Solution

  • I added the dispatch function to props:

    [<Pojo>]
    type Model = {
        isLoading:                  bool
        processDocumentation:       ProcessDocumentationDto
        valuesForFilterDropdown:    DropdownFilterValues
        scopeOfFilter:              ScopeOfFilter
        expandedMenuItemsIds:       string list
    }
    
    [<Pojo>]
    type DocumentationProps = {
        model:      Model
        dispatch:   Msg -> unit
    }
    

    create the view:

    let root model dispatch =
      let inline documentation props = ofType<Documentation,_,_> props []
    
      let pageHtml =
        function
        | Home -> Home.View.root model.home (HomeMsg >> dispatch)
        | Documentation -> documentation { model.documentation with dispatch = (DocumentationMsg >> dispatch)}
    

    and then I call it this way:

    RequestProcessDocumentation |> this.props.dispatch