Skip to content
This repository was archived by the owner on May 6, 2024. It is now read-only.

Commit

Permalink
fix: checkboxes remains tick after navigating out of page
Browse files Browse the repository at this point in the history
  • Loading branch information
yuhaopro committed Mar 13, 2024
1 parent d8e4e04 commit b79d051
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 93 deletions.
48 changes: 45 additions & 3 deletions db.json
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,28 @@
{
"id": "4",
"title": "My Favourites",
"booklist": []
"booklist": [
{
"key": "222697",
"slug": "the-shining-girls",
"title": "The Shining Girls",
"author": {
"cachedImage": {},
"name": "Lauren Beukes",
"slug": "lauren-beukes",
"key": "lauren-beukes",
"image": ""
},
"image": "https://storage.googleapis.com/hardcover/editions/30399651/9485519905660492-lg_url.jpg",
"description": "The girl who wouldn’t die. Hunting a killer who shouldn’t exist. Chicago 1931. Violent drifter Harper Curtis stumbles upon a house that hides a secret as shocking as his own twisted nature: it opens onto other times. Harper uses it to stalk his ‘shining girls’ across decades – and cut the fire out of them. He’s the perfect killer. Unstoppable. Untraceable. Until one of his victims survives and turns the hunt around. Chicago, 1992. Kirby Mazrachi’s determination to find the man who tried to kill her has taken over her life. The cops no longer return her calls. Her mother copes by writing morbid children’s books. Her only ally is Dan, the burnt-out ex-homicide reporter who covered her case. As Kirby closes in on her would-be killer, what she finds is ... impossible. Murders scattered across the decades along with evidence that makes no sense. Meanwhile, Harper is closing in on her too",
"source": "hc",
"series": {
"key": "",
"slug": "",
"name": ""
}
}
]
},
{
"id": "5",
Expand Down Expand Up @@ -247,7 +268,28 @@
{
"id": "6",
"title": "My dogs",
"booklist": []
"booklist": [
{
"key": "222697",
"slug": "the-shining-girls",
"title": "The Shining Girls",
"author": {
"cachedImage": {},
"name": "Lauren Beukes",
"slug": "lauren-beukes",
"key": "lauren-beukes",
"image": ""
},
"image": "https://storage.googleapis.com/hardcover/editions/30399651/9485519905660492-lg_url.jpg",
"description": "The girl who wouldn’t die. Hunting a killer who shouldn’t exist. Chicago 1931. Violent drifter Harper Curtis stumbles upon a house that hides a secret as shocking as his own twisted nature: it opens onto other times. Harper uses it to stalk his ‘shining girls’ across decades – and cut the fire out of them. He’s the perfect killer. Unstoppable. Untraceable. Until one of his victims survives and turns the hunt around. Chicago, 1992. Kirby Mazrachi’s determination to find the man who tried to kill her has taken over her life. The cops no longer return her calls. Her mother copes by writing morbid children’s books. Her only ally is Dan, the burnt-out ex-homicide reporter who covered her case. As Kirby closes in on her would-be killer, what she finds is ... impossible. Murders scattered across the decades along with evidence that makes no sense. Meanwhile, Harper is closing in on her too",
"source": "hc",
"series": {
"key": "",
"slug": "",
"name": ""
}
}
]
}
]
}
}
131 changes: 43 additions & 88 deletions src/components/Book.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import {
ReactNode,
createContext,
useContext,
useEffect,
useMemo,
useState,
} from 'react'
Expand Down Expand Up @@ -368,106 +369,60 @@ export const BookDropdown = ({ button, children }: BookDropdown) => {
Book.DropdownMenu = BookDropdown

export const BookDropdownMock = ({ button, children }: BookDropdown) => {
const { book } = useBookContext()

/**
* Created list
* @description
* A book in already in any Created list, can be in another
*/
const [coreListId, setCoreListId] = useState<string>('To Read')

/**
* Created list
* @description
* A book in already in any Created list, can be in another
*/
const [createdListIds, setCreatedListIds] = useState<Set<string>>(
new Set<string>([]),
)

/** @description get collections from collection api */
const { data, isLoading, isError } = useGetCollectionsQuery()
const [updateCollection] = useUpdateCollectionMutation()
const { book } = useBookContext();

// State management
const [coreListId, setCoreListId] = useState<string>();
const [createdListIds, setCreatedListIds] = useState<Set<string>>(() => {
const storedListIds = localStorage.getItem('createdListIds');
return storedListIds ? new Set(JSON.parse(storedListIds)) : new Set();
});
useEffect(() => {
localStorage.setItem('createdListIds', JSON.stringify(Array.from(createdListIds)));
}, [createdListIds]);

// Fetch and Filter Collections
const { data, isLoading, isError } = useGetCollectionsQuery();
const [updateCollection] = useUpdateCollectionMutation();

if (isLoading || isError) {
logger({ breakpoint: '[Book.tsx:394]' }, 'Loading or Error')
return null
logger({ breakpoint: '[Book.tsx:394]' }, 'Loading or Error');
return null;
}
// Helper Functions
const isCoreCollection = (collection: CollectionQueryResponse) =>
['To Read', 'Reading', 'Completed'].includes(collection.title);

// separate the data to core and created collections
const toReadCollection = data!.filter(
(collection: CollectionQueryResponse) => collection.title === 'To Read',
)
const readingCollection = data!.filter(
(collection: CollectionQueryResponse) => collection.title === 'Reading',
)
const completedCollection = data!.filter(
(collection: CollectionQueryResponse) => collection.title === 'Completed',
)
const coreLists = [
...toReadCollection,
...readingCollection,
...completedCollection,
]
const createdLists = data!.filter(
(collection: CollectionQueryResponse) =>
collection.title !== 'To Read' &&
collection.title !== 'Reading' &&
collection.title !== 'Completed',
)

// const handleAddBookToCoreList = () => {
const isCreatedCollection = (collection: CollectionQueryResponse) =>
!isCoreCollection(collection);

// }
const coreLists = data!.filter(isCoreCollection);
const createdLists = data!.filter(isCreatedCollection);

// Adding Book to Created Lists
const handleAddBookToCreatedList = (isAdded: boolean, id: string) => {
const collection = createdLists.find(
(collection: CollectionQueryResponse) => collection.id === id,
)
logger({ breakpoint: '[Book.tsx:416]' }, 'Collection found', collection)
const { booklist } = collection!

if (!isAdded) {
// add the book to the list
const updatedBookList = [...booklist, book]
const params = { booklist: updatedBookList }
logger(
{ breakpoint: '[Book.tsx:423]' },
'booklist Passed',
updatedBookList,
book,
)

updateCollection({ id, params: params })
} else {
// remove book from list
const updatedBookList = booklist.filter(
(booklistBook: Book) => booklistBook.key !== book.key,
)
logger(
{ breakpoint: '[Book.tsx:426]' },
'booklist Passed',
updatedBookList,
)

updateCollection({ id, params: { booklist: updatedBookList } })
}
}
const collection = createdLists.find((c) => c.id === id);
if (!collection) return;

const { booklist } = collection;
const updatedBookList = isAdded
? booklist.filter((booklistBook) => booklistBook.key !== book.key)
: [...booklist, book];

updateCollection({ id, params: { booklist: updatedBookList } });
};

// Dropdown Render Logic
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="default"
size="icon"
{...button}
>
<Button variant="default" size="icon" {...button}>
<StackIcon />
</Button>
</DropdownMenuTrigger>

<DropdownMenuContent>
<DropdownMenuLabel className="small py-0 text-xs capitalize text-muted-foreground">
<DropdownMenuLabel className="small py-0 text-xs capitalize text-muted-foreground">
{book.title}
</DropdownMenuLabel>

Expand Down Expand Up @@ -513,7 +468,7 @@ export const BookDropdownMock = ({ button, children }: BookDropdown) => {
const listIds = new Set(createdListIds)
const isAdded = listIds.has(id)
logger(
{ breakpoint: '[Book.tsx:344]' },
{ breakpoint: '[Book.tsx:523]' },
'Triggered onSelect',
)
handleAddBookToCreatedList(isAdded, id)
Expand Down Expand Up @@ -551,8 +506,8 @@ export const BookDropdownMock = ({ button, children }: BookDropdown) => {
{children}
</DropdownMenuContent>
</DropdownMenu>
)
}
);
};

Book.DropdownMenuMock = BookDropdownMock

Expand Down
2 changes: 0 additions & 2 deletions src/pages/book/-[slug]/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,6 @@ const BookLayout = () => {
<main
className={cn(
'page-container',

'flex flex-col gap-8',
'place-items-center',
'*:w-full',
Expand Down Expand Up @@ -257,7 +256,6 @@ const BookLayout = () => {
</span>
</Link>
</p>

<Book.DropdownMenuMock />
</aside>
</div>
Expand Down

0 comments on commit b79d051

Please sign in to comment.