Learn HalogenGHC loads in the background

7. Fetching data

A component fetching server data needs to display loading, success and failure states. This example uses Halogen.Net.Fetch, a wrapper around browser fetch, to load quotes from data/quotes.json.

Three states

The state records whether the request is pending, succeeded or failed:

data State a = Loading | Done a | Failed Text

render handles all three cases. handleAction first calls put Loading, fetches the data, then stores Done with the quotes or Failed with an explanation. H.onInitialize (handleAction (Load "data/quotes.json")) starts the initial request when the component mounts.

Fetching

getQuotes performs the request in IO:

  1. Fetch.request Fetch.GET url constructs a request. Relative URLs resolve against the page's base URL.
  2. Fetch.fetch sends it and waits for status and headers. Browser failures, such as network errors, return Left with an error name and message.
  3. HTTP errors such as 404 still return Right response. With OverloadedRecordDot, read response.ok to check success and response.status for the numeric code.
  4. Fetch.text reads the body. Aeson.eitherDecodeStrictText decodes it into [Quote]. The generic FromJSON instance uses record field names as JSON keys.

Waiting without stopping the page

handleAction calls getQuotes through H.async, because the request waits. The request waits on a separate Haskell thread while the component loop keeps rendering and handling actions. Once the response arrives, the handler resumes. An action that does not wait goes in H.sync instead.

Exercise

Import Halogen.HTML.Events qualified as HE and add two buttons above the quotes:

  • Reload triggers Load "data/quotes.json". It briefly shows Loading... before displaying the quotes again.
  • Load a missing file triggers Load "data/missing.json". The server returns 404, and the component shows the failure status.
Lesson.hs
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}

module Lesson (component) where

import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.State (put)
import Data.Aeson qualified as Aeson
import Data.Text (Text)
import Data.Text qualified as T
import GHC.Generics (Generic)
import Halogen qualified as H
import Halogen.HTML qualified as HH
import Halogen.Net.Fetch qualified as Fetch

data Quote = Quote {quote :: Text, author :: Text}
  deriving (Generic)

instance Aeson.FromJSON Quote

data State a = Loading | Done a | Failed Text

data Action = Load Text

component :: forall q o m. (MonadIO m) => H.Component q () o m
component =
  H.component initialState render [H.onInitialize (handleAction (Load "data/quotes.json")), H.onAction handleAction]
  where
    initialState _ = pure Loading
    render state =
      HH.div_
        [ case state of
            Loading -> HH.p_ [HH.text "Loading..."]
            Failed message -> HH.p_ [HH.text ("Failed: " <> message)]
            Done quotes -> HH.ul_ [HH.li_ [HH.text (q.quote <> " (" <> q.author <> ")")] | q <- quotes]
        ]
    handleAction (Load url) = do
      put Loading
      result <- H.async (liftIO (getQuotes url))
      put (either Failed Done result)

-- Runs in IO, and waits: first for the response, then for its body.
getQuotes :: Text -> IO (Either Text [Quote])
getQuotes url = do
  fetched <- Fetch.fetch (Fetch.request Fetch.GET url)
  case fetched of
    Left err -> pure (Left (err.name <> ": " <> err.message))
    Right response
      | not response.ok -> pure (Left (url <> ": status " <> T.pack (show response.status)))
      | otherwise -> do
          body <- Fetch.text response
          pure $ case body of
            Left err -> Left err.message
            Right json -> either (Left . T.pack) Right (Aeson.eitherDecodeStrictText json)

The compiler loads once the page has started.

Your component will appear here after compilation.