김재형

Implement FileList component

import React, { Fragment } from "react";
import { Switch, Route, Redirect } from "react-router-dom";
import React, { useEffect } from "react";
import { Switch, Route, Redirect, useHistory } from "react-router-dom";
import { Login } from "auth/Login";
import { useAuth } from "auth/useAuth";
import { useAuth, TokenContext } from "auth/useAuth";
import { Page } from "layout/Page";
import { FileList } from "file/FileList";
export function App() {
const { token, login } = useAuth();
const root = token?.user.rootFolder;
const history = useHistory();
useEffect(() => {
if (root) {
history.push(`/folder/${root}`);
}
}, [history, root]);
return (
<Fragment>
<Switch>
<Route path="/login">
<Login login={login} />
</Route>
</Switch>
{token === null && <Redirect to="/login" />}
</Fragment>
<Switch>
<Route path="/login">
<Login login={login} />
</Route>
<Route>
{token !== null ? (
<TokenContext.Provider value={token}>
<Page>
<Switch>
<Route path="/folder/:id">
<FileList />
</Route>
</Switch>
</Page>
</TokenContext.Provider>
) : (
<Redirect to="/login" />
)}
</Route>
</Switch>
);
}
......
import React from "react";
import { useParams } from "react-router-dom";
import { useFileList } from "./useFileList";
export function FileList() {
const id = useParams<{ id: string }>().id;
const { data } = useFileList(id);
return <div>{JSON.stringify(data, null, 2)}</div>;
}
import { useState, useCallback, useEffect } from "react";
import ky from "ky";
interface FileListResponse {
data: FileItem & {
list: FileItem[];
};
}
interface FileItem {
is_folder: boolean;
name: string;
file_type: "folder" | "file";
path: string;
parent: number;
user_id: number;
size: number;
is_deleted: boolean;
created_time: string | null;
updated_time: string;
status: boolean;
id: number;
}
interface Token {
accessToken: string;
refreshToken: string;
expiration: Date;
user: {
id: number;
username: string;
name: string;
totalSize: number;
currentSize: number;
rootFolder: number;
};
}
export function useFileList(id: string) {
const [data, setData] = useState<FileListResponse | null>(null);
const reload = useCallback(async () => {
const response = await ky
.get(`/items/${id}/children/`)
.json<FileListResponse>();
setData(response);
}, [id]);
useEffect(() => {
reload();
}, [reload]);
return { data, reload };
}
import { useRef, useEffect } from "react";
export function usePrevious<T>(value: T) {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
});
return ref.current as T;
}