Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

Episode.js

49 lines1.5 KB

1import React from "react";
2import { Typography, Link } from "@material-ui/core";
3import { Link as RouterLink } from "react-router-dom";
4import { useParams } from "react-router";
5import { useQuery } from "react-query";
6import fetch from "./fetch";
7​
8function Episode() {
9 const { episodeId } = useParams();
10 const { data, status } = useQuery(`episode-${episodeId}`, () =>
11 fetch(`https://rickandmortyapi.com/api/episode/${episodeId}`)
12 );
13​
14 if (status === "loading") return <p>Loading...</p>;
15 if (status === "error") return <p>Error :(</p>;
16​
17 return (
18 <div>
19 <Typography variant="h2">{data.name}</Typography>
20 <Typography variant="body1">{data.air_date}</Typography>
21 <br />
22 <Typography variant="h4">Characters</Typography>
23 {data.characters.map(character => {
24 const characterUrlParts = character.split("/").filter(Boolean);
25 const characterId = characterUrlParts[characterUrlParts.length - 1];
26 return <Character id={characterId} key={characterId} />;
27 })}
28 </div>
29 );
31​
32function Character({ id }) {
33 const { data, status } = useQuery(`character-${id}`, () =>
34 fetch(`https://rickandmortyapi.com/api/character/${id}`)
35 );
36​
37 if (status === "loading") return <p>Loading...</p>;
38 if (status === "error") return <p>Error :(</p>;
39​
40 return (
41 <article key={id}>
42 <Link component={RouterLink} to={`/characters/${id}`}>
43 <Typography variant="h6">{data.name}</Typography>
44 </Link>
45 </article>
46 );
48​
49export default Episode;