Mayank
Mayank

Reputation: 954

Update data value in Elm

I am trying to change object data value before reusing it.

I have a data type

type alias Definition =
    { title : String
    , description : String
    , image : String

    }

-- using original data coming from API

    getDescription : Tag -> (Definition -> a) -> String -> Maybe Definition -> Html a
    getDescription tag msg name def =
            case def of
                Just d ->
                        div [] [
                            div [] [ text d.title ]
                            , div [] [ text d.description ]

-- trying to change description with removeDescription function      
                            , div [] [ newDescription (removeDescription d) ] 

                            ]
                Nothing ->
                    div [] [ text "name"]





newDescription : Definition -> Html a
newDescription d =
    div [] [ 
        div[] [d.title] 
        , div[] [ d.description ]        -- trying to use new description
        ]

-- This function fails

removeDescription : Definition -> Definition
removeDescription d = 
        { d | d.description = '' }   -- This fails 

I have tried

String.replace

but it still fails

Is it even possible to change data like this way considering Elm make sure data immutability ?

Upvotes: 0

Views: 201

Answers (1)

THK
THK

Reputation: 701

I'd be more certain if you also posted Elm's (helpful!) error message, but it seems like in your example you want description instead of d.description when you update the record (which is syntactic sugar for returning a new record with other values unchanged -- as you note, Elm features purity / data immutability).

Example in the Elm REPL using your record type:

> d = Definition "Test" "Hello World" "0000"
{ description = "Hello World", image = "0000", title = "Test" }
    : Definition
> d2 = {d | description = ""}
{ description = "", image = "0000", title = "Test" }
    : { description : String, image : String, title : String }

There are some more examples from the Elm docs

Upvotes: 3

Related Questions