From a41b26371c2841717764753f271f4e910c907bd5 Mon Sep 17 00:00:00 2001 From: dm1sh Date: Thu, 15 Jul 2021 21:49:09 +0500 Subject: [PATCH] Added book list reading for bookshelf --- src/Bookshelf/index.tsx | 10 +++++++--- src/utils/localStorage.ts | 40 ++++++++++++++++++++++++++++++++------- 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/src/Bookshelf/index.tsx b/src/Bookshelf/index.tsx index 5ee981b..1253c4c 100644 --- a/src/Bookshelf/index.tsx +++ b/src/Bookshelf/index.tsx @@ -1,14 +1,18 @@ -import React, { useState } from "react"; +import React, { useEffect, useState } from "react"; import { IBook } from "@type/book"; import styles from "./Bookshelf.module.css"; -import list from "@assets/bookList.json"; import { BookItem } from "./BookItem"; import { AddBook } from "./AddBook"; +import { readBooks } from "@utils/localStorage"; export const Bookshelf = () => { - const [books, setBooks] = useState(list); + const [books, setBooks] = useState([]); + + useEffect(() => { + setBooks(readBooks()); + }, []); return (
diff --git a/src/utils/localStorage.ts b/src/utils/localStorage.ts index 3b3a0aa..3ef9b67 100644 --- a/src/utils/localStorage.ts +++ b/src/utils/localStorage.ts @@ -1,14 +1,40 @@ import { IBook } from "@type/book"; import { isArrOfStr } from "@type/utils"; +import { validateResponse } from "../api"; +import { BookItem } from "../Bookshelf/BookItem"; -export const saveBook = (bookObj: IBook, key: string): void => { +const readBookList = ( + cb: (bookList: string[]) => T, + defaultValue: T extends void ? undefined : T +) => { 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)); - } + if (isArrOfStr(bookList)) return cb(bookList); + return defaultValue; }; + +export const saveBook = (bookObj: IBook, key: string) => + readBookList((bookList) => { + if (!bookList.includes(key)) { + const newBookList = [key, ...bookList]; + + localStorage.setItem("list", JSON.stringify(newBookList)); + localStorage.setItem(key, JSON.stringify(bookObj)); + } + }, undefined); + +export const readBooks = (): IBook[] => + readBookList( + (bookList) => + bookList + .map((hash) => JSON.parse(localStorage.getItem(hash) || "{}")) + .filter((e) => { + try { + return validateResponse(e); + } catch (err) { + return false; + } + }), + [] + );