API fetching
In this tutorial, we will fetch a list of all first generation Pokémon (the best ones, by the way) from the PokeAPI and create a dynamic page for each of them.
Fetch all the Pokémon
Let's start by fetching the data on the root page.
Since we want to render the Pokémon on the server, we need to implement the logic in the index.rs
file.
Clear the index.rs
file and paste:
The first argument is always
req: Request
, which contains all the request data, such as the query parameters and HTTP headers. The other arguments represent the ApplicationState and are optional.
After doing this, the terminal will complain for two reasons:
- We haven't imported the
reqwest
crate - The second argument
fetch: Client
hasn't been defined as global state yet.
Let's fix these errors in the next section.
Application state
Compared to JavaScript runtimes, Tuono is lightning fast because it only loads the features that you need for your project.
You can load them in the ApplicationState
inside the ./src/app.rs
file. This file is executed just once at the very beginning of your application.
For the tutorial we will use Reqwest, which is one of the most popular HTTP libraries.
To install it, run this command in your terminal:
A new entry was added to your Cargo.toml
file.
The
Cargo.toml
file is the manifest of your application and contains Rust's dependencies (similar to thepackage.json
file for JavaScript).
Now let's define the ApplicationState
in the ./src/app.rs
file.
Now that the fetch: Client
argument is available in the handler, the previously reported errors should be resolved.
In the next section, we'll render the fetched data in the browser.
Handling the page UI
With the Pokémon correctly fetched and hydrated on the client, we can finally render them.
Replace the content of the index.tsx
file with the following snippet:
Time to refresh the browser! It's still a bit ugly, but all the Pokémon are finally on the screen!
Edit page