In my project, I am getting an array of objects from api, and I want to divide the array into 3 three arrays based on the value of the shelf
property of each
array element which is an object. Now for doing that I am using formatBooks
function inside the same component.
Later on I am passing this formatBooks
function as prop to other component which calls this function.
I was hoping if there is any better by making another component and place the formatBooks inside that. I wanted to know a better and elegant way of doing things like this.
class BooksApp extends React.Component {
state = {
books: [],
searchResults: [],
newBooksFromSearch: [],
}
//format the books array
formatBooks = () => {
const currentlyReading = []
const read = []
const wantToRead = []
this.state.books.forEach( item => {
if(item.shelf === "currentlyReading" || item.shelf === "Currently Reading"){
item.setShelf = "Currently Reading"
currentlyReading.push(item)
}
if(item.shelf === "read" || item.shelf === "Read" ){
item.setShelf = "Read"
read.push(item)
}
if(item.shelf === "wantToRead" || item.shelf === "Want to Read"){
item.setShelf = "Want to Read"
wantToRead.push(item)
}
})
return(
{
currentlyReading: currentlyReading,
read: read,
wantToRead: wantToRead
}
)
}