forked from udacity/reactnd-project-myreads-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
115 lines (106 loc) · 2.91 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import React from 'react';
import { Route, Link } from 'react-router-dom';
import * as BooksAPI from './BooksAPI';
import Shelf from './Shelf';
import Search from './Search';
import './App.css';
const shelfList = [
{
id: 'currentlyReading',
label: 'Currently Reading',
},
{
id: 'wantToRead',
label: 'Want to Read',
},
{
id: 'read',
label: 'Read',
},
];
class BooksApp extends React.Component {
state = {
booksInShelf: {}, // Contains books that are assigned to any shelf
};
componentDidMount() {
BooksAPI.getAll().then((books) => {
// Store books with IDs as keys, so that they can be easily accessed by ID
const booksWithId = {};
books.forEach((book) => {
booksWithId[book.id] = book;
});
this.setState(() => ({
booksInShelf: booksWithId,
}));
});
}
moveBook = (book, newShelfId) => {
BooksAPI.update(book, newShelfId).then(() => {
this.setState((prevState) => {
const bookId = book.id;
book.shelf = newShelfId; // Update shelf
this.isShelf(newShelfId)
? (prevState.booksInShelf[bookId] = book) // Updated or new book
: delete prevState.booksInShelf.bookId; // Delete book if not in shelf anymore
return prevState;
});
});
};
getBooksByShelf = (shelfId) => {
const { booksInShelf } = this.state;
return Object.keys(booksInShelf)
.map((bookId) => booksInShelf[bookId])
.filter((book) => book.shelf === shelfId);
};
isShelf = (shelfId) => {
return shelfList.map((shelf) => shelf.id).includes(shelfId);
};
render() {
const { booksInShelf } = this.state;
return (
<div className='app'>
<Route
exact
path='/'
render={() => (
<div className='list-books'>
<div className='list-books-title'>
<h1>MyReads</h1>
</div>
<div className='list-books-content'>
<div>
{shelfList.map((shelf) => (
<Shelf
key={shelf.id}
shelf={shelf}
shelfList={shelfList}
booksThisShelf={this.getBooksByShelf(shelf.id)}
booksAnyShelf={booksInShelf}
onBookMove={this.moveBook}
/>
))}
</div>
</div>
<div className='open-search'>
<Link to='/search'>
<button>Add a book</button>
</Link>
</div>
</div>
)}
/>
<Route
path='/search'
render={() => (
<Search
shelfList={shelfList}
booksAnyShelf={booksInShelf}
onBookMove={this.moveBook}
/>
)}
/>
</div>
);
}
}
export default BooksApp;