Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/error boundary #54

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions cypress/integration/home/error-fallback.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { streamsRegex } from "../../consts/urlRegexes";

describe("Home > Error Fallback", () => {
it("should throw error fallback when request fails", () => {
cy.intercept(streamsRegex, {
statusCode: 400,
});

cy.visit(Cypress.env("hostUrl"));

cy.get(".chakra-text").eq(2).should("have.text", "Oops! Algo de errado não está certo");
cy.get(".chakra-text")
.eq(3)
.should("have.text", "Não conseguimos carregar o que você estava procurando 😔");
cy.get("button").should("have.text", "Tente novamente");
});
});
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"react-apexcharts": "^1.3.9",
"react-cookie": "^4.1.1",
"react-dom": "^17.0.2",
"react-error-boundary": "^3.1.4",
"react-ga": "^3.3.0",
"react-icons": "^4.3.1",
"react-router-dom": "^6.2.1",
Expand Down Expand Up @@ -87,9 +88,8 @@
"lint-staged": ">=12",
"prettier": "^2.5.1"
},

"lint-staged": {
"src/**/*": [
"src/**/!*.css": [
"yarn lint --fix"
]
},
Expand Down
1 change: 0 additions & 1 deletion src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
body {
background-color: #33374D !important;
height: 100%;
padding-bottom: 200px;
}

.logo-title {
Expand Down
29 changes: 18 additions & 11 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,38 @@
import React, { useEffect } from "react";
import ReactGA from "react-ga";
import { Routes, Route } from "react-router-dom";
import "./App.css";
import { ErrorBoundary } from "react-error-boundary";

import ToPage from "./pages/to/ToPage";
import "./App.css";

import Home from "./pages/Home";
import About from "./pages/About";
import Stats from "./pages/Estatisticas";
import Supporters from "./pages/Supporters";
import ToPage from "./pages/to/ToPage";

import ReactGA from "react-ga";
import LandingLayout from "./components/layouts/LandingLayout";
import ErrorFallback from "./components/sections/ErrorFallback";

function App() {
useEffect(() => {
ReactGA.pageview(window.location.pathname + window.location.search);
});

return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/stats" element={<Stats />} />
<Route path="/sobre" element={<About />} />
<Route path="/agradecimentos" element={<Supporters />} />
{/* <Route path="/profile" element={<ProfilePage />} />
<LandingLayout>
<ErrorBoundary FallbackComponent={ErrorFallback}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/stats" element={<Stats />} />
<Route path="/sobre" element={<About />} />
<Route path="/agradecimentos" element={<Supporters />} />
{/* <Route path="/profile" element={<ProfilePage />} />
<Route path="/login" element={<LoginPage />} /> */}
<Route path="/to/:username" element={<ToPage />} />
</Routes>
<Route path="/to/:username" element={<ToPage />} />
</Routes>
</ErrorBoundary>
</LandingLayout>
);
}

Expand Down
6 changes: 3 additions & 3 deletions src/components/layouts/LandingLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ type Props = {

export default function LandingLayout({ children }: Props) {
return (
<Stack>
<Stack h="100vh">
<Header />
<Box m={[0, "center"]}>
<Container maxW="container.xl" mb="10">
<Box m={[0, "center"]} flex="1">
<Container maxW="container.xl" mb="10" h="full">
{children}
</Container>
</Box>
Expand Down
25 changes: 25 additions & 0 deletions src/components/sections/ErrorFallback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Center, VStack, Text, Button, Box } from "@chakra-ui/react";
import { RepeatIcon } from "@chakra-ui/icons";
import { FallbackProps } from "react-error-boundary";

const ErrorFallback = ({ resetErrorBoundary }: FallbackProps) => {
return (
<Center h="full">
<VStack gap="2">
<Box textAlign="center">
<Text fontSize="2xl" color="white" fontWeight="semibold">
Oops! Algo de errado não está certo
</Text>
<Text fontSize="lg" color="white">
Não conseguimos carregar o que você estava procurando 😔
</Text>
</Box>
<Button rounded="sm" onClick={resetErrorBoundary} leftIcon={<RepeatIcon />}>
Tente novamente
</Button>
</VStack>
</Center>
);
};

export default ErrorFallback;
15 changes: 6 additions & 9 deletions src/hooks/useAxios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,12 @@ const api = axios.create({

export function useAxios() {
const apiGet = useCallback(
async <Response, Data = void>(
endpoint: string,
config?: AxiosRequestConfig<Data>,
) => {
const { data } = await api.get<
Response,
AxiosResponse<Response, Data>,
Data
>(endpoint, config);
async <Response, Data = void>(endpoint: string, config?: AxiosRequestConfig<Data>) => {
const { data } = await api.get<Response, AxiosResponse<Response, Data>, Data>(
endpoint,
config,
);

return data;
},
[],
Expand Down
5 changes: 2 additions & 3 deletions src/pages/About.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,10 @@ import {
Text,
Wrap,
} from "@chakra-ui/react";
import LandingLayout from "../components/layouts/LandingLayout";

export default function About() {
return (
<LandingLayout>
<>
<Box mt={8} mb={4}>
<Heading>Sobre</Heading>
<Text color={"gray.500"}>Saiba mais sobre o projeto!</Text>
Expand Down Expand Up @@ -133,6 +132,6 @@ export default function About() {
</AccordionPanel>
</AccordionItem>
</Accordion>
</LandingLayout>
</>
);
}
28 changes: 17 additions & 11 deletions src/pages/Estatisticas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,31 @@ import {
import { useAxios } from "../hooks/useAxios";
import { endpoints } from "../service/api";
import { Stats, StatsSummary, StatsSummaryDefault } from "../types";

import LandingLayout from "../components/layouts/LandingLayout";
import { useErrorHandler } from "react-error-boundary";

export default function StatsPage() {
const { apiGet } = useAxios();
const handleError = useErrorHandler();

const [isLoading, setIsLoading] = useState(false);
const [stats, setStats] = useState<Stats[]>([]);
const [statsSummary, setStatsSummary] = useState<StatsSummary>(StatsSummaryDefault);

const loadData = useCallback(async () => {
setIsLoading(true);
try {
setIsLoading(true);

const statsList = await apiGet<Stats[]>(endpoints.stats.url);
const statsSummaryList = await apiGet<StatsSummary>(endpoints.stats_summary.url);
const statsList = await apiGet<Stats[]>(endpoints.stats.url);
const statsSummaryList = await apiGet<StatsSummary>(endpoints.stats_summary.url);

setStats(statsList);
setStatsSummary(statsSummaryList);
setIsLoading(false);
}, [apiGet]);
setStats(statsList);
setStatsSummary(statsSummaryList);
} catch (error) {
handleError(error);
} finally {
setIsLoading(false);
}
}, [apiGet, handleError]);

useEffect(() => {
loadData();
Expand All @@ -61,7 +67,7 @@ export default function StatsPage() {
};

return (
<LandingLayout>
<>
<Box mt={8} mb={4}>
<Heading>Estatísticas</Heading>
<Text color={"gray.500"}>Saiba mais sobre o projeto!</Text>
Expand Down Expand Up @@ -109,6 +115,6 @@ export default function StatsPage() {
</Center>
</>
)}
</LandingLayout>
</>
);
}
51 changes: 29 additions & 22 deletions src/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,21 @@ import {

import type { Channel, Tag } from "../types";

import LandingLayout from "../components/layouts/LandingLayout";
import { SkeletonListCard } from "../components/sections/SkeletonListCard";
import { SkeletonListTags } from "../components/sections/SkeletonListTags";
import Card from "../components/ui/Card";
import Mosaic from "../components/sections/Mosaic";
import { useAxios } from "../hooks/useAxios";
import { endpoints } from "../service/api";
import { useSearchParams } from "react-router-dom";
import { useErrorHandler } from "react-error-boundary";

export default function Home() {
const REFRESH_TIME_IN_SECONDS = 120;
const { apiGet } = useAxios();
const buttonSize = useBreakpointValue({ base: "sm", md: "md" });
const [isLargerThan1000px] = useMediaQuery("(min-width: 1000px)");
const handleError = useErrorHandler();

const [isMosaicMode, setIsMosaicMode] = useState(false);
const [channels, setChannels] = useState<Channel[]>([]);
Expand All @@ -49,20 +50,24 @@ export default function Home() {
const isRefetching = isLoading && hasData;

const loadData = useCallback(async () => {
setIsFetching(true);
try {
setIsFetching(true);

const [channelsList, tagsList, vodsList] = await Promise.all([
apiGet<Channel[]>(endpoints.channels.url),
apiGet<Tag[]>(endpoints.tags.url),
apiGet<Channel[]>(endpoints.vods.url),
]);
const [channelsList, tagsList, vodsList] = await Promise.all([
apiGet<Channel[]>(endpoints.channels.url),
apiGet<Tag[]>(endpoints.tags.url),
apiGet<Channel[]>(endpoints.vods.url),
]);

setChannels(channelsList);
setTags(tagsList);
setVods(vodsList);

setIsFetching(false);
}, [apiGet]);
setChannels(channelsList);
setTags(tagsList);
setVods(vodsList);
} catch (error) {
handleError(error);
} finally {
setIsFetching(false);
}
}, [apiGet, handleError]);

const handleShuffleClick = () => {
const channel = channels[Math.floor(Math.random() * channels.length)];
Expand Down Expand Up @@ -102,18 +107,20 @@ export default function Home() {

useEffect(() => {
const tagNames = searchParams.get("tags");
if (tagNames && tags.length) {
if (tagNames && tags?.length) {
const tagsNamesArray = decodeURIComponent(tagNames).split(",");
const newSelectedTags = tagsNamesArray.map((tag) => tags.find((t) => t.name === tag)) as Tag[];
const newSelectedTags = tagsNamesArray.map((tag) =>
tags.find((t) => t.name === tag),
) as Tag[];
setSelectedTags(newSelectedTags);
}
}, [searchParams, tags]);

const filterChannelsByTags = (channels: Channel[], selectedTags: Tag[]) => {
const filterChannelsByTags = (channels: Channel[] | undefined, selectedTags: Tag[]) => {
if (selectedTags.length === 0) {
return channels;
}
const filteredChannels = channels.filter((channel) => {
const filteredChannels = channels?.filter((channel) => {
return selectedTags.every((selectedTag) => channel.tags?.includes(selectedTag.id));
});

Expand All @@ -126,7 +133,7 @@ export default function Home() {
);

return (
<LandingLayout>
<>
<Flex mt={8} mb={4} gap={2} alignItems="center" wrap="wrap">
<Box>
<Heading display="flex" flexDirection="row" alignItems="center">
Expand Down Expand Up @@ -204,7 +211,7 @@ export default function Home() {
<SkeletonListTags />
) : (
<>
{tags.map((tag) => {
{tags?.map((tag) => {
const isTagSelected = selectedTags.some((t) => t.id === tag.id);
return (
<TagChakra
Expand Down Expand Up @@ -239,7 +246,7 @@ export default function Home() {
<SkeletonListCard />
) : (
<SimpleGrid columns={{ sm: 2, md: 3, lg: 4 }} gap={4}>
{filteredChannels.map((channel) => (
{filteredChannels?.map((channel) => (
<Card
key={channel.id}
channel={channel}
Expand All @@ -260,7 +267,7 @@ export default function Home() {
<SkeletonListCard />
) : (
<SimpleGrid columns={{ sm: 2, md: 3, lg: 4 }} gap={4}>
{vods.map((channel) => (
{vods?.map((channel) => (
<Card
key={channel.id}
channel={channel}
Expand All @@ -273,6 +280,6 @@ export default function Home() {
)}

{isMosaicMode && <Mosaic channels={selectedChannels} />}
</LandingLayout>
</>
);
}
Loading