export const App = () => {
const [items, setItems] = React.useState(undefined)
const [error, setError] = React.useState(undefined)
React.useEffect(() => {
fetch('/api/item')
.then(rep => rep.json())
.then(items => setItems(items))
.catch(e => setError(e))
}, [])
return error !== undefined
? (<p class="error">{error.message}</p>)
: items === undefined
? (<p>Loading...</p>)
: items.map(item => {
return (
<div key={item.id}>
<p>{item.title}</p>
<span class="small">
{item.description}
</span>
</div>
)
})
}
|
type Item = { id :: String
, title :: String
, description :: String
}
data State
= StateEmpty
| StateErrored Error
| StateGotItems (Array Item)
data Action = ActionInit
renderItem item =
div [] [ p [] [text item.title]
, span
[className "small"]
[text item.description]
]
renderApp StateEmpty = p [] [text "Loading..."]
renderApp (StateErrored e) = p [className "error"] [text (message e)]
renderApp (StateGotItems items) = map renderItem items
action ActionInit = do
response <- fetch (URL "/api/item") {method: Get}
jsonString <- text response
itemsOrError <- readJSON jsonString
case itemsOrError of
Right items -> put (StateGotItems items)
Left error -> put (StateErrored error)
app = mkComponent
{ initialState: StateEmpty
, render: renderApp
, eval:
mkEval ( defaultEval { handleAction = action
, initialize: Just ActionInit
}
)
}
|