Added processed book saving to localstorage

This commit is contained in:
Dmitriy Shishkov 2021-07-15 19:12:35 +05:00
parent c25873158d
commit 74b3cc725d
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060
6 changed files with 33 additions and 10 deletions

View File

@ -21,7 +21,7 @@ module.exports = {
devOptions: {
open: "none",
},
alias: { "@assets": "./src/assets" },
alias: { "@assets": "./src/assets", "@utils": "./src/utils" },
exclude: ["**/node_modules/**/*", "**/*.test.*"],
env: {
// API_URL: "https://publitebackend.dmitriy.icu",

View File

@ -3,6 +3,7 @@ import React, { useState } from "react";
import plusIcon from "@assets/plus.svg";
import styles from "./UploadForm.module.css";
import { submitFile, validateResponse, validState } from "../api";
import { saveBook } from "@utils/localStorage";
export const UploadForm = () => {
const [error, setError] = useState("");
@ -17,8 +18,10 @@ export const UploadForm = () => {
const res = await submitFile(file);
setLoading(false);
console.log(validateResponse(res));
if (validateResponse(res)) {
// TODO: save book to localstorage
saveBook(res, res.hash || Date.now().toString());
// TODO: redirect to main menu
}
}

View File

@ -1,10 +1,9 @@
export const requiredBookProps = ["title", "author", "content"] as const;
export const optionalBookProps = ["cover", "hash"] as const;
export type IBook =
| {
[key in typeof requiredBookProps[number]]: string;
}
| {
[key in typeof optionalBookProps[number]]: string | undefined;
};
export type IBook = {
[key in typeof requiredBookProps[number]]: string;
} &
{
[key in typeof optionalBookProps[number]]: string | undefined;
};

7
src/types/utils.ts Normal file
View File

@ -0,0 +1,7 @@
export const isArrOfStr = (obj: unknown): obj is string[] => {
if (Array.isArray(obj)) {
for (const el of obj) if (typeof el !== "string") return false;
return true;
}
return false;
};

14
src/utils/localStorage.ts Normal file
View File

@ -0,0 +1,14 @@
import { IBook } from "../types/book";
import { isArrOfStr } from "../types/utils";
export const saveBook = (bookObj: IBook, key: string): void => {
const bookListStr = localStorage.getItem("list") || "[]";
const bookList: unknown = JSON.parse(bookListStr);
if (isArrOfStr(bookList) && !bookList.includes(key)) {
const newBookList = [key, ...bookList];
localStorage.setItem("list", JSON.stringify(newBookList));
localStorage.setItem(key, JSON.stringify(bookObj));
}
};

View File

@ -10,6 +10,6 @@
"module": "ES2020",
"moduleResolution": "node",
"resolveJsonModule": true,
"paths": { "@assets/*": ["src/assets/*"] }
"paths": { "@assets/*": ["./src/assets/*"], "@utils/*": ["./src/utils/*"] }
}
}