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 Textrender 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:
Fetch.request Fetch.GET urlconstructs a request. Relative URLs resolve against the page's base URL.Fetch.fetchsends it and waits for status and headers. Browser failures, such as network errors, returnLeftwith an errornameandmessage.- HTTP errors such as 404 still return
Right response. WithOverloadedRecordDot, readresponse.okto check success andresponse.statusfor the numeric code. Fetch.textreads the body.Aeson.eitherDecodeStrictTextdecodes it into[Quote]. The genericFromJSONinstance 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.