I’ve started with Elm and want to get images from Trefle API when searched for plant but I keep getting the “Could not fetch image” error.
I do use my own access token but i replaced it here with “MY_API_TOKEN” to keep it private.
Can you help me to understand the problem in my code?
Thank you.
I’ve tried to get a more detailed error message but then my code crashed because I am quite new with using elm and in the webdevelopment field.
module Main exposing (..)
import Browser
import Html exposing (Html, button, div, img, input, text)
import Html.Attributes exposing (placeholder, src, type_)
import Html.Events exposing (onClick, onInput)
import Http
import Json.Decode exposing (Decoder, field, list, string)
import Maybe exposing (withDefault, map)
type alias Model =
{ searchTerm : String
, imageUrl : String
, error : String
}
init : () -> ( Model, Cmd Msg )
init _ =
( { searchTerm = "", imageUrl = "", error = "" }, Cmd.none )
type Msg
= UpdateSearchTerm String
| FetchImage
| ReceiveImage (Result Http.Error String)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
UpdateSearchTerm term ->
( { model | searchTerm = term }, Cmd.none )
FetchImage ->
( model, fetchPlantImage model.searchTerm )
ReceiveImage result ->
case result of
Ok url ->
( { model | imageUrl = url, error = "" }, Cmd.none )
Err _ ->
( { model | error = "Failed to fetch image." }, Cmd.none )
view : Model -> Html Msg
view model =
div []
[ input [ placeholder "Enter plant name", onInput UpdateSearchTerm ] []
, button [ onClick FetchImage ] [ text "Search" ]
, if model.imageUrl /= "" then
img [ src model.imageUrl ] []
else
text ""
, if model.error /= "" then
div [] [ text model.error ]
else
text ""
]
fetchPlantImage : String -> Cmd Msg
fetchPlantImage searchTerm =
let
url =
"https://trefle.io/api/v1/plants/search?token=MY_API_TOKEN&q=" ++ searchTerm
decodeImageUrl : Decoder String
decodeImageUrl =
field "data" (list (field "image_url" string))
|> Json.Decode.map (withDefault "" << map identity << List.head)
in
Http.get
{ url = url
, expect = Http.expectJson ReceiveImage decodeImageUrl
}
main : Program () Model Msg
main =
Browser.element
{ init = init
, update = update
, subscriptions = _ -> Sub.none
, view = view
}
lani2000 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.