Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ELM update two fields in model

How can i update two fields in model at once? Now i have request that return me an alias with {price: Float, productId: Int} I need to update two fields in model like model.price and model.productId

I looking for something like that, but its not work (ofc)

    case maybeProduct of
        Just product ->
       ( { model | price = product.price && 
           model | productId = product.productId}
            , Cmd.none
            )
        Nothing ->
            ( model
               , Cmd.none
             )

I found some info where advice that I can create two functions (Model -> Product -> Model) and do something like:

setPrice : Model -> Product -> Model
setPrice model product =
    { model | price = product.price }

setProductId : Model -> Product -> Model
setProductId model product =
    { model | companyId = product.productId }

                Just product ->
                        let
                            newModel =
                                product
                                    |> setPrice model
                                    |> setProductId model
                        in
                        ( newModel
                        , Cmd.none
                        )
                    Nothing ->
                        ( model
                           , Cmd.none
                         )

but something dont work. It looks like product dont passing in each function

i recieve

The argument is:

Model

But (|>) is piping it a function that expects:

{ companyId : Int, price : Float }

Where i mistake? Or maybe there is different way to update two fields in model?

like image 441
Stefan B Avatar asked Jan 02 '23 14:01

Stefan B


1 Answers

How to update two fields at once:

Do something like this (this excludes commands by the way - you can add that in to suit your requirements):

{ model | price = new_price, productId = newProductId}

If you want to add Commands then you can do this:

({ model | price = new_price, productId = newProductId}, nameOfYourCommand)

Documentation:

Here is a link that @JackLeow very kindly posted: https://elm-lang.org/docs/records#updating-records

like image 105
BenKoshy Avatar answered Jan 11 '23 14:01

BenKoshy