Day 3
Today we'll fetch and display remote data, add a theme switcher, and handle currency conversion.
Dark mode
Add a button that switches the theme of the app. We can do this by toggling the CSS class theme--dark
on the root (html
) element in a useEffect
hook. (This is one of many ways to do theming)
Tip: You can use
document.documentElement.classList
to access the list of CSS classes on the root element. You can then call.add
and.remove
to modify the list.
Fetching data
We'll be using a REST API that returns static data: https://my-json-server.typicode.com/dabbott/dashboard-json-server
Endpoints:
We can access an individual article or info object by its id, e.g. /info/1
.
Fetching /info/1
Start by fetching and displaying the first info resource. You should use useFetch.ts
and api.ts
.
Tip: Since
useFetch
is generic, you may want to specialize it at the callsite for better type checking, e.g.useFetch<InfoResource>(...)
When the resource is loading, display a loading state (e.g. the string "Loading..."
). You may also want to show an error message in the case where it fails to load.
Fetching /articles
Next, fetch all articles using useFetch
.
Trade
Now that we can fetch the current price of BTC (via /info
), we can properly convert between USD and BTC. Validate the number at a basic level (validating a number perfectly is fairly tricky - it's OK if you don't handle every edge case).
Hint: see parseFloat and isNaN for parsing/validating numbers.
App
Putting it all together, we should be able to fetch data for our entire initial screen.