Going to another page no longer triggers page reaload

This commit is contained in:
Dmitriy Shishkov 2021-07-15 20:22:04 +05:00
parent ebecd1a974
commit 86dd039d57
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060
5 changed files with 22 additions and 11 deletions

View File

@ -13,12 +13,10 @@ const routes: Route[] = [
{ Component: UploadForm, path: "/upload" },
];
export const App = () => {
return (
<div className={styles.container}>
<Router routes={routes} startPath="/list" DefaultComponent={Err404} />
</div>
);
};
export const App = () => (
<div className={styles.container}>
<Router routes={routes} startPath="/list" DefaultComponent={Err404} />
</div>
);
export default App;

View File

@ -2,10 +2,17 @@ import React from "react";
import plusIcon from "@assets/plus.svg";
import styles from "./AddBook.module.css";
import { BASE_URL } from "../../constants";
import { goTo } from "../../router/goTo";
export const AddBook = () => {
return (
<button className={styles.container}>
<button
onClick={() => {
goTo(BASE_URL + "/upload");
}}
className={styles.container}
>
<img src={plusIcon} className={styles.plus} />
<h1 className={styles.caption}>Add book</h1>
</button>

View File

@ -4,6 +4,8 @@ import plusIcon from "@assets/plus.svg";
import styles from "./UploadForm.module.css";
import { submitFile, validateResponse, validState } from "../api";
import { saveBook } from "@utils/localStorage";
import { BASE_URL } from "../constants";
import { goTo } from "../router/goTo";
export const UploadForm = () => {
const [error, setError] = useState("");
@ -22,7 +24,7 @@ export const UploadForm = () => {
if (validateResponse(res)) {
saveBook(res, res.hash || Date.now().toString());
// TODO: redirect to main menu
goTo(BASE_URL + "/list");
}
}
} catch (err) {

4
src/router/goTo.ts Normal file
View File

@ -0,0 +1,4 @@
export const goTo = (
href: string = window.location.href,
nextTitle: string = document.title
) => window.history.pushState({}, nextTitle, href);

View File

@ -3,6 +3,7 @@ import React from "react";
import { BASE_URL } from "../constants";
import { Route } from "@type/router";
import { Err404 } from "./404";
import { goTo } from "./goTo";
interface IRouterProps {
routes: Route[];
@ -16,8 +17,7 @@ export const Router = ({
DefaultComponent,
}: IRouterProps) => {
const currPath = window.location.pathname;
if (startPath && currPath === "/")
window.location.href = BASE_URL + startPath;
if (startPath && currPath === "/") goTo(BASE_URL + startPath);
for (const route of routes) {
if (currPath === route.path || currPath === route.path + "/")