Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elm StartApp decoding http request

Tags:

elm

I'm trying to decode a http request to pokéapi in Elm, using StartApp as a base. Though I'm getting an error I don't really know how to fix:

The right argument of (|>) is causing a type mismatch.

76│     Http.getString testUrl
77│     |> Task.map parseMon
78│>    |> Task.map OnPokemonLoaded

(|>) is expecting the right argument to be a:

    Task Http.Error (Result String Pokemon) -> a

But the right argument is:

    Task Http.Error (Result Http.Error Pokemon) -> Task Http.Error Action

The code it's talking about is:

-- Fetching test mon
testUrl : String
testUrl = "http://pokeapi.co/api/v2/pokemon/1/"


fetchTest : Effects.Effects Action
fetchTest =
    Http.getString testUrl
    |> Task.map parseMon
    |> Task.map OnPokemonLoaded --line 78
    |> Effects.task

parseMon : String -> Result String Pokemon.Pokemon
parseMon json = Json.Decode.decodeString Pokemon.decoder json

OnPokemonLoaded is one of my actions: OnPokemonLoaded (Result Http.Error Pokemon). Pokemon.decoder is a simple json decoder: decoder : Decoder Pokemon.

I'm still new to Elm, and only just trying out StartApp and Effects. The error seems to explain the problem pretty well, but I'm still a little lost as to how it should work.

So, how should I request and decode the json properly?

like image 756
The Oddler Avatar asked Mar 06 '26 20:03

The Oddler


1 Answers

The use of Http.getString and parseMon is unnecessary. Instead, you can use Http.get and pass your Json decoder, then map it to a Result to get the functionality you're after:

fetchTest : Effects.Effects Action
fetchTest =
  Http.get Pokemon.decoder testUrl
    |> Task.toResult
    |> Task.map OnPokemonLoaded
    |> Effects.task
like image 171
Chad Gilbert Avatar answered Mar 10 '26 01:03

Chad Gilbert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!