The Oddler
The Oddler

Reputation: 6728

Elm StartApp decoding http request

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?

Upvotes: 3

Views: 240

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36385

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

Upvotes: 4

Related Questions