Open History to see the last commit
1import React from "react";
2import {
3 Typography,
4 Link,
5 Table,
6 TableBody,
7 TableCell,
8 TableContainer,
9 TableHead,
10 TableRow,
11 Paper
12} from "@material-ui/core";
13import { Link as RouterLink } from "react-router-dom";
14import { useParams } from "react-router";
15import { useQuery } from "react-query";
16import fetch from "./fetch";
17β
18function Character() {
19 const { characterId } = useParams();
20 const { status, data } = useQuery(`character-${characterId}`, () =>
21 fetch(`https://rickandmortyapi.com/api/character/${characterId}`)
22 );
23β
24 if (status === "loading") return <p>Loading...</p>;
25 if (status === "error") return <p>Error :(</p>;
26β
27 const locationUrlPars = data.location.url.split("/").filter(Boolean);
28 const locationId = locationUrlPars[locationUrlPars.length - 1];
29β
30 return (
31 <div>
32 <Typography variant="h2">{data.name}</Typography>
33 <TableContainer component={Paper} style={{ maxWidth: "400px" }}>
34 <Table size="small" aria-label="simple table">
35 <TableHead>
36 <TableRow>
37 <TableCell>Feature</TableCell>
38 <TableCell>Value</TableCell>
39 </TableRow>
40 </TableHead>
41 <TableBody>
42 <TableRow>
43 <TableCell>Gender</TableCell>
44 <TableCell>{data.gender}</TableCell>
45 </TableRow>
46 <TableRow>
47 <TableCell>Status</TableCell>
48 <TableCell>{data.status}</TableCell>
49 </TableRow>
50 <TableRow>
51 <TableCell>Species</TableCell>
52 <TableCell>{data.species}</TableCell>
53 </TableRow>
54 <TableRow>
55 <TableCell>Origin</TableCell>
56 <TableCell>{data.origin.name}</TableCell>
57 </TableRow>
58 <TableRow>
59 <TableCell>Location</TableCell>
60 <TableCell>
61 <Location id={locationId} />
62 </TableCell>
63 </TableRow>
64 </TableBody>
65 </Table>
66 </TableContainer>
67 <br />
68 <Typography variant="h4">Episodes</Typography>
69 {data.episode.map(episode => {
70 const episodeUrlParts = episode.split("/").filter(Boolean);
71 const episodeId = episodeUrlParts[episodeUrlParts.length - 1];
72β
73 return <Episode id={episodeId} key={`episode-${episodeId}`} />;
74 })}
75 </div>
76 );
77}
78β
79function Episode({ id }) {
80 const { data, status } = useQuery(`episode-${id}`, () =>
81 fetch(`https://rickandmortyapi.com/api/episode/${id}`)
82 );
83β
84 if (status !== "success") {
85 return null;
86 }
87β
88 return (
89 <article key={id}>
90 <Link component={RouterLink} to={`/episodes/${id}`}>
91 <Typography variant="h6">
92 {data.episode}. {data.name} - {data.air_date}
93 </Typography>
94 </Link>
95 </article>
96 );
97}
98β
99function Location({ id }) {
100 const { data, status } = useQuery(`location-${id}`, () =>
101 fetch(`https://rickandmortyapi.com/api/location/${id}`)
102 );
103β
104 if (status === "loading") return <p>Loading...</p>;
105 if (status === "error") return <p>Error :(</p>;
106β
107 return (
108 <>
109 {data.name} - {data.type}
110 </>
111 );
112}
113β
114export default Character;