3
votes

I have an app where a user can create projects. The currentProject in the model is a Maybe Project type with the initial value set to Nothing (since there may be no projects created yet by that user).

type alias Project =
    { name : String }

type alias Model =
    { user : User
    , currentProject : Maybe Project
    }

This is in the init for the Model:

currentProject = Nothing

I then have a dropdown where the user can select a project. Upon selecting it the onClick calls the following update:

type Msg
    = ...
    | SetProject Project

The update function that I try to run looks like this:

SetProject project ->
    case project of
       Just project ->
         ( { model | currentProject = project }, Cmd.none )

       Nothing ->
         ( model, Cmd.none )

I get an error because project is of type Project and not Maybe Project.

I know the project exists because it's coming from an existing list of projects in the app. But, I cannot set currentProject to type Project because I need to initialize the Model with Nothing.

So, how can I update the Maybe Project record with type Project?

2

2 Answers

5
votes

Use the Just constructor:

SetProject project ->
     ( { model | currentProject = Just project }, Cmd.none )
3
votes

Your message says you are expecting a Project type, but then you are pattern matching on it to check to see if it is a (Maybe Project) but it isn't. So, either pass in a Maybe Project in your msg or change your update function to be this.

SetProject project ->
    ( { model | currentProject = Just project }, Cmd.none )