Feature/swr for library screens (#186)
* Wrap data fetching in library and manga screen with swr for better dev and user experience. Refactor some API calls and data handling. Add manual refresh to manga detail. * Fix manga card layout * Fix refresh button position on small screens * Revert "Fix manga card layout" This reverts commit d85da3d8385e1ef64feed1789e4cd4591c8bd563. * Fix manga not setting title * Move chapters loading to Manga component, join data fetching, add auto online fetch if fetched data is old * Revert some changes
This commit is contained in:
@@ -6,10 +6,10 @@
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { Tab, Tabs } from '@mui/material';
|
||||
import React, { useContext, useEffect, useState } from 'react';
|
||||
import React, {
|
||||
useContext, useEffect, useState,
|
||||
} from 'react';
|
||||
import NavbarContext from 'components/context/NavbarContext';
|
||||
import client from 'util/client';
|
||||
import cloneObject from 'util/cloneObject';
|
||||
import EmptyView from 'components/util/EmptyView';
|
||||
import LoadingPlaceholder from 'components/util/LoadingPlaceholder';
|
||||
import TabPanel from 'components/util/TabPanel';
|
||||
@@ -17,18 +17,25 @@ import LibraryOptions from 'components/library/LibraryOptions';
|
||||
import LibraryMangaGrid from 'components/library/LibraryMangaGrid';
|
||||
import AppbarSearch from 'components/util/AppbarSearch';
|
||||
import { useQueryParam, NumberParam } from 'use-query-params';
|
||||
import useSWR from 'swr';
|
||||
import UpdateChecker from '../components/library/UpdateChecker';
|
||||
|
||||
interface IMangaCategory {
|
||||
category: ICategory
|
||||
mangas: IManga[]
|
||||
isFetched: boolean
|
||||
}
|
||||
|
||||
export default function Library() {
|
||||
const { data: tabsData, error: tabsError } = useSWR<ICategory[]>('/api/v1/category');
|
||||
const tabs = tabsData ?? [];
|
||||
|
||||
const [tabSearchParam, setTabSearchParam] = useQueryParam('tab', NumberParam);
|
||||
|
||||
const activeTab = tabs.find((t) => t.order === tabSearchParam) ?? tabs[0];
|
||||
const { data: mangaData, error: mangaError } = useSWR<IManga[]>(`/api/v1/category/${activeTab?.id}`, {
|
||||
isPaused: () => activeTab == null,
|
||||
});
|
||||
const mangas = mangaData ?? [];
|
||||
|
||||
const { setTitle, setAction } = useContext(NavbarContext);
|
||||
useEffect(() => {
|
||||
setTitle('Library'); setAction(
|
||||
setTitle('Library');
|
||||
setAction(
|
||||
<>
|
||||
<AppbarSearch />
|
||||
<LibraryOptions />
|
||||
@@ -37,64 +44,19 @@ export default function Library() {
|
||||
);
|
||||
}, []);
|
||||
|
||||
const [tabs, setTabs] = useState<IMangaCategory[]>();
|
||||
|
||||
const [tabNum, setTabNum] = useState<number>(0);
|
||||
const [tabSearchParam, setTabSearchParam] = useQueryParam('tab', NumberParam);
|
||||
|
||||
// a hack so MangaGrid doesn't stop working. I won't change it in case
|
||||
// if I do manga pagination for library..
|
||||
const [lastPageNum, setLastPageNum] = useState<number>(1);
|
||||
|
||||
const handleTabChange = (newTab: number) => {
|
||||
setTabNum(newTab);
|
||||
setTabSearchParam(newTab);
|
||||
setTabSearchParam(newTab === 0 ? undefined : newTab);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
client.get('/api/v1/category')
|
||||
.then((response) => response.data)
|
||||
.then((categories: ICategory[]) => {
|
||||
const categoryTabs = categories.map((category) => ({
|
||||
category,
|
||||
mangas: [] as IManga[],
|
||||
isFetched: false,
|
||||
}));
|
||||
setTabs(categoryTabs);
|
||||
if (categoryTabs.length > 0) {
|
||||
if (
|
||||
tabSearchParam !== undefined
|
||||
&& tabSearchParam !== null
|
||||
&& !Number.isNaN(tabSearchParam)
|
||||
&& categories.some((category) => category.order === Number(tabSearchParam))
|
||||
) {
|
||||
handleTabChange(Number(tabSearchParam!));
|
||||
} else { handleTabChange(categoryTabs[0].category.order); }
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
if (tabsError != null) {
|
||||
return <EmptyView message="Could not load categories" messageExtra={tabsError?.message ?? tabsError} />;
|
||||
}
|
||||
|
||||
// fetch the current tab
|
||||
useEffect(() => {
|
||||
if (tabs !== undefined) {
|
||||
tabs.forEach((tab, index) => {
|
||||
if (tab.category.order === tabNum && !tab.isFetched) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-shadow
|
||||
client.get(`/api/v1/category/${tab.category.id}`)
|
||||
.then((response) => response.data)
|
||||
.then((data: IManga[]) => {
|
||||
const tabsClone = cloneObject(tabs);
|
||||
tabsClone[index].mangas = data;
|
||||
tabsClone[index].isFetched = true;
|
||||
|
||||
setTabs(tabsClone);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [tabs?.length, tabNum]);
|
||||
|
||||
if (tabs === undefined) {
|
||||
if (tabsData == null) {
|
||||
return <LoadingPlaceholder />;
|
||||
}
|
||||
|
||||
@@ -102,57 +64,57 @@ export default function Library() {
|
||||
return <EmptyView message="Your Library is empty" />;
|
||||
}
|
||||
|
||||
let toRender;
|
||||
if (tabs.length > 1) {
|
||||
// eslint-disable-next-line max-len
|
||||
const tabDefines = tabs.map((tab) => (<Tab label={tab.category.name} value={tab.category.order} />));
|
||||
|
||||
const tabBodies = tabs.map((tab) => (
|
||||
<TabPanel index={tab.category.order} currentIndex={tabNum}>
|
||||
<LibraryMangaGrid
|
||||
mangas={tab.mangas}
|
||||
hasNextPage={false}
|
||||
lastPageNum={lastPageNum}
|
||||
setLastPageNum={setLastPageNum}
|
||||
message="Category is Empty"
|
||||
isLoading={!tab.isFetched}
|
||||
/>
|
||||
</TabPanel>
|
||||
));
|
||||
|
||||
// Visual Hack: 160px is min-width for viewport width of >600
|
||||
const scrollableTabs = window.innerWidth < tabs.length * 160;
|
||||
toRender = (
|
||||
<>
|
||||
<Tabs
|
||||
key={tabNum}
|
||||
value={tabNum}
|
||||
onChange={(e, newTab) => handleTabChange(newTab)}
|
||||
indicatorColor="primary"
|
||||
textColor="primary"
|
||||
centered={!scrollableTabs}
|
||||
variant={scrollableTabs ? 'scrollable' : 'fullWidth'}
|
||||
scrollButtons
|
||||
allowScrollButtonsMobile
|
||||
>
|
||||
{tabDefines}
|
||||
</Tabs>
|
||||
{tabBodies}
|
||||
</>
|
||||
);
|
||||
} else {
|
||||
const mangas = tabs.length === 1 ? tabs[0].mangas : [];
|
||||
toRender = (
|
||||
if (tabs.length === 1) {
|
||||
return (
|
||||
<LibraryMangaGrid
|
||||
mangas={mangas}
|
||||
hasNextPage={false}
|
||||
lastPageNum={lastPageNum}
|
||||
setLastPageNum={setLastPageNum}
|
||||
message="Your Library is empty"
|
||||
isLoading={!tabs[0].isFetched}
|
||||
isLoading={activeTab != null && mangaData == null && mangaError == null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return toRender;
|
||||
// Visual Hack: 160px is min-width for viewport width of >600
|
||||
const scrollableTabs = window.innerWidth < tabs.length * 160;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Tabs
|
||||
key={activeTab.order}
|
||||
value={activeTab.order}
|
||||
onChange={(e, newTab) => handleTabChange(newTab)}
|
||||
indicatorColor="primary"
|
||||
textColor="primary"
|
||||
centered={!scrollableTabs}
|
||||
variant={scrollableTabs ? 'scrollable' : 'fullWidth'}
|
||||
scrollButtons
|
||||
allowScrollButtonsMobile
|
||||
>
|
||||
{tabs.map((tab) => (
|
||||
<Tab key={tab.id} label={tab.name} value={tab.order} />
|
||||
))}
|
||||
</Tabs>
|
||||
{tabs.map((tab) => (
|
||||
<TabPanel key={tab.order} index={tab.order} currentIndex={activeTab.order}>
|
||||
{tab === activeTab && (mangaError
|
||||
? (
|
||||
<EmptyView message="Could not load manga" messageExtra={mangaError?.message ?? mangaError} />
|
||||
)
|
||||
: (
|
||||
<LibraryMangaGrid
|
||||
mangas={mangas}
|
||||
hasNextPage={false}
|
||||
lastPageNum={lastPageNum}
|
||||
setLastPageNum={setLastPageNum}
|
||||
message="Category is Empty"
|
||||
isLoading={mangaData == null}
|
||||
/>
|
||||
))}
|
||||
</TabPanel>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,43 +5,70 @@
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import React, { useEffect, useState, useContext } from 'react';
|
||||
import React, {
|
||||
useCallback, useEffect, useContext, useState, useRef,
|
||||
} from 'react';
|
||||
import useSWR from 'swr';
|
||||
import { Box } from '@mui/system';
|
||||
import MangaDetails from 'components/MangaDetails';
|
||||
import NavbarContext from 'components/context/NavbarContext';
|
||||
import client from 'util/client';
|
||||
import { fetcher } from 'util/client';
|
||||
import LoadingPlaceholder from 'components/util/LoadingPlaceholder';
|
||||
import ChapterList from 'components/chapter/ChapterList';
|
||||
import { useParams } from 'react-router-dom';
|
||||
|
||||
const AUTOFETCH_AGE = 60 * 60 * 24; // 24 hours
|
||||
|
||||
export default function Manga() {
|
||||
const { setTitle } = useContext(NavbarContext);
|
||||
useEffect(() => { setTitle('Manga'); }, []); // delegate setting topbar action to MangaDetails
|
||||
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const autofetchedRef = useRef(false);
|
||||
|
||||
const [manga, setManga] = useState<IManga>();
|
||||
const { data: manga, error, mutate: mutateManga } = useSWR<IManga>(`/api/v1/manga/${id}/?onlineFetch=false`);
|
||||
const { data: chaptersData, mutate: mutateChapters } = useSWR<IChapter[]>(`/api/v1/manga/${id}/chapters?onlineFetch=false`);
|
||||
|
||||
const [fetchingOnline, setFetchingOnline] = useState(false);
|
||||
const fetchOnline = useCallback(async () => {
|
||||
setFetchingOnline(true);
|
||||
await Promise.all([
|
||||
fetcher(`/api/v1/manga/${id}/?onlineFetch=true`)
|
||||
.then((res) => mutateManga(res, { revalidate: false })),
|
||||
fetcher(`/api/v1/manga/${id}/chapters?onlineFetch=true`)
|
||||
.then((res) => mutateChapters(res, { revalidate: false })),
|
||||
]);
|
||||
setFetchingOnline(false);
|
||||
}, [mutateManga, mutateChapters, id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (manga === undefined || !manga.freshData) {
|
||||
client.get(`/api/v1/manga/${id}/?onlineFetch=${manga !== undefined}`)
|
||||
.then((response) => response.data)
|
||||
.then((data: IManga) => {
|
||||
setManga(data);
|
||||
setTitle(data.title);
|
||||
});
|
||||
// Automatically fetch manga from source if data is older then 24 hours
|
||||
// Automatic fetch is done only once, to prevent issues when server does
|
||||
// not update age for some reason (ie. error on source side)
|
||||
if (manga == null) return;
|
||||
if (
|
||||
manga.inLibrary
|
||||
&& (manga.age > AUTOFETCH_AGE || manga.chaptersAge > AUTOFETCH_AGE)
|
||||
&& autofetchedRef.current === false
|
||||
) {
|
||||
autofetchedRef.current = true;
|
||||
fetchOnline();
|
||||
}
|
||||
}, [manga]);
|
||||
|
||||
useEffect(() => {
|
||||
setTitle(manga?.title ?? 'Manga');
|
||||
}, [manga?.title]);
|
||||
|
||||
return (
|
||||
<Box sx={{ display: { md: 'flex' }, overflow: 'hidden' }}>
|
||||
<LoadingPlaceholder
|
||||
shouldRender={manga !== undefined}
|
||||
component={MangaDetails}
|
||||
componentProps={{ manga }}
|
||||
/>
|
||||
|
||||
<ChapterList id={id} />
|
||||
{!manga && !error && <LoadingPlaceholder />}
|
||||
{manga && (
|
||||
<MangaDetails
|
||||
refreshing={fetchingOnline}
|
||||
manga={manga}
|
||||
onRefresh={fetchOnline}
|
||||
/>
|
||||
)}
|
||||
<ChapterList id={id} chaptersData={chaptersData} onRefresh={() => mutateChapters()} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user