JSFiddle - React, Tailwind, and code Playground
by ruhul105
JavaScript
import React from 'react'
import * as BooksAPI from './BooksAPI'
import './App.css'
import ListBooks from './ListBooks'
import SearchBooks from './SearchBooks'
import {Route} from 'react-router-dom'
class BooksApp extends React.Component {
// three states are defined for three shelfs.
state ={
books:[]
}
// this function get our book data by API .
componentDidMount() {
this.getdata();
}
getdata(){
return(
BooksAPI.getAll().then((books) => {
const currentlyReading = books.filter(book => book.shelf === "currentlyReading")
const wantToRead = books.filter(book => book.shelf === "wantToRead")
const read = books.filter(book => book.shelf === "read")
this.setState({currentlyReading,wantToRead,read})
}))
}
// This function helps us to updating the data in the three shelfs.
updatedata = (book, shelf) => {
if (book.shelf !== shelf) {
BooksAPI.update(book, shelf).then(() => {
book.shelf = shelf
// Filter out the book and append it to the end of the list
// so it appears at the end of whatever shelf it was added to.
this.setState(state => ({
books: state.books.filter(b => b.id !== book.id).concat([ book ])
}))
})
}
}
render() {
return (
<div className="app">
<Route exact path="/" component={ListBooks} onShelfChange={this.updatedata()}/>
<Route path="/search" component={SearchBooks} onShelfChange={this.updatedata()}/>
</div>
)
}
}
export default BooksApp