import { ApolloConsumer, useQuery, useSubscription } from '@apollo/client' import { union } from 'lodash' import { ALL_BOOKS } from '../queries' import { BOOK_ADDED } from '../queries.js' import { useState } from 'react' import { useEffect } from 'react' const getAllGenres = (books) => { const allGenres = union(...books.map(book => book.genres)) return allGenres } const Books = () => { const [selectedGenre, setSelectedGenre] = useState(null) const [books, setBooks] = useState([]) const [allGenres, setAllGenres] = useState([]) const result = useQuery(ALL_BOOKS, { variables: { genre: selectedGenre } }) useEffect(() => { if (result.data) { const allBookGenres = getAllGenres(result.data.allBooks) setAllGenres(allBookGenres) } }, []) useEffect(() => { if (result.data) { setBooks(result.data.allBooks) } }, [result.data]) useSubscription(BOOK_ADDED, { onData: ({ data }) => { const addedBook = data.data.bookAdded setBooks((prevBooks) => { const updatedBooks = prevBooks.concat(addedBook) return selectedGenre ? updatedBooks.filter((book) => book.genres.includes(selectedGenre)) : updatedBooks }) }, }) if (result.loading) { return
| Author | Published | |
|---|---|---|
| {a.title} | {a.author.name} | {a.published} |