API fetching
The goal is to use the PokeAPI to list all the Pokémon of the first generation (the best one, btw) and then reserve a dynamic page for each one separately.
Fetch all the Pokémon
To start, let’s fetch all of them from the root page. Since we want to render them on the server side, we are going to need to implement the logic in the index.rs
file.
Clear the index.rs
file and paste:
The first argument is always the request
req: Request
which contains all the request's data like the query parameters and the HTTP headers. The rest of the arguments represents the ApplicationState and are optional.
The terminal will complain now for two reasons:
- We don't have imported any
reqwest
crate - The second argument
fetch: Client
has not been defined yet as global state.
Let's fix these in the next section.
Application state
Compared to the common Javascript runtimes, Tuono is fast because only the features you need for your project will be loaded.
You can load them in the ApplicationState
of your app inside the ./src/app.rs
file. This is the file that will be executed just once at the very beginning of your application.
For the tutorial we will use Reqwest which is one of the most famous HTTP library.
To install it just run in your terminal:
A new entry has just been added to your Cargo.toml
file.
The
Cargo.toml
is the manifest file of your application, in which you handle Rust's dependencies (similarly as the package.json for Javascript).
Now let's define the ApplicationState
in the ./src/app.rs
file.
Now the fetch: Client
argument is available in the above defined handler, and the terminal should not complain anymore.
Let's see in the next section how to show the fetched data on the browser.
Handling the page UI
Now the Pokémon are correctly fetched and hydrated on the client side, so we can actually use them. Clear the index.tsx
file and paste:
Refresh the browser now! A bit ugly, but all the Pokémon are finally printed on screen!
Edit page