In this challenge, you will fetch a character from the Star Wars API with SWR
and combine this with dynamic routes.
- Start the development server and make yourself familiar with the application.
- Open the browser: there are links to four characters, but only the first one (Luke Skywalker) currently works.
- Click the link to Luke (localhost:3000/characters/1): there is a character displayed together with some information.
- In your Code editor, switch to
pages/characters/1.js
: it renders theCard
component, but uses hard coded data.
Your task is to fetch a character from the Star Wars API. Use SWR
to do so and implement a loading as well as an error state.
You can use the following hints as guideline:
SWR
is already installed, so you just have to import it.- Switch to
./pages/characters/1.js
:- fetch only the first character using https://swapi.dev/api/people/1;
- instead of the hard coded
/1
, interpolate theid
variable. - implement a loading state;
- to implement a proper error state based on an error object, you need to adapt the fetcher function as explained in the SWR docs.
- Adapt the return statement so that you pass the correct fetched data to the
Card
component. - When you are done, reload the browser with
characters/1
: it should now return the fetched data of Luke Skywalker.- Note: Because we declared the
id
variable with1
, it's currently not possible to fetch another character by changing the url to, e.g.,characters/2
. We will fix this when implementing dynamic routes in the next step.
- Note: Because we declared the
✨ Congratulations, you have fetched an API with the help of SWR
!
By now, there is only one static route /1
fetching one static character. Let's use a dynamic route to fetch different characters based on the query parameter!
- Rename the
/pages/characters/1.js
file into/pages/characters/[id].js
. - Replace the variable
const id = 1
: use theuseRouter
hook to access theid
fromrouter.query
. - Check the browser again:
localhost:3000/characters/1
should now return Luke Skywalker as well, while changing theid
parameter should return a different character. - Go back to the overview page `pages/index.js: now, all links should fetch and display the correct character.
- You only have to touch the following files:
./pages/index.js
,./pages/characters/1.js
.
To work locally, please install the dependencies using npm i
first.
Run npm run dev
to start a development server and open the displayed URL in a browser.
Use npm run test
to run the tests.
Select the "Preview: 3000" tab to view this project.
Select the "Tests: logs" tab to view the tests.
The
npm run dev
andnpm run test
scripts run automatically.
You can use the following commands:
npm run dev
to start a development servernpm run build
to build the projectnpm run start
to start a production servernpm run test
to run the testsnpm run lint
to run the linter