Using Task in init

If you need this, you can do it with the current structure by marking the model as uninitialized.

type alias Size = 
    { width : Float
    , height : Float
    }


type alias Model =
    { size : Maybe Size 
    }

init : () -> ( Model, Cmd Msg )
init _ =
    (Model Nothing, Browser.Dom.getViewport |> Task.perform Initialize )

type Msg 
    = Initialize Browser.Dom.Viewport
    ...

update : Msg -> Model -> (Model, Cmd Msg) 
update msg model = 
    case msg of 
        Initialize viewport -> 
            (Model {width = viewport.width, height = viewport.height}, Cmd.none)
        ...

view : Model -> Html Msg 
view model = 
     Maybe.map viewForSize model.size 
     |> Maybe.withDefault (text "")

If you don’t like the Maybe you can use a flag isInitialized or you can make the Model a custom type like type Model = Initializing | Initialized State.

2 Likes