From 0358a9e130db17f42efdaecefd276fa495dc7301 Mon Sep 17 00:00:00 2001 From: Savy011 <106910589+Savy011@users.noreply.github.com> Date: Wed, 24 May 2023 18:55:46 +0530 Subject: [PATCH] Finished Ex 8.22 --- Part_8/library-frontend/src/App.js | 2 +- Part_8/library-frontend/src/components/Books.js | 16 ++++++++++++++-- .../library-frontend/src/components/NewBook.js | 4 ++-- .../src/components/Recommended.js | 17 ++++++++++++++--- 4 files changed, 31 insertions(+), 8 deletions(-) diff --git a/Part_8/library-frontend/src/App.js b/Part_8/library-frontend/src/App.js index 8e31b69..f5a2735 100644 --- a/Part_8/library-frontend/src/App.js +++ b/Part_8/library-frontend/src/App.js @@ -8,7 +8,7 @@ import { useApolloClient, useSubscription } from '@apollo/client' import Recommend from './components/Recommended' import { ALL_BOOKS, BOOK_ADDED } from './queries' -export const updateCache = (cache, query, addedBook) => { +const updateCache = (cache, query, addedBook) => { const uniqById = a => { let seen = new Set() return a.filter(item => { diff --git a/Part_8/library-frontend/src/components/Books.js b/Part_8/library-frontend/src/components/Books.js index 8e841c6..7cbaff5 100644 --- a/Part_8/library-frontend/src/components/Books.js +++ b/Part_8/library-frontend/src/components/Books.js @@ -1,6 +1,7 @@ -import { ApolloConsumer, useQuery } from '@apollo/client' +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' @@ -16,7 +17,7 @@ const Books = () => { const result = useQuery(ALL_BOOKS, { variables: { genre: selectedGenre } }) - + useEffect(() => { if (result.data) { const allBookGenres = getAllGenres(result.data.allBooks) @@ -30,6 +31,17 @@ const Books = () => { } }, [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
genres: {genres.join(', ')}
Genres: {genres.join(', ')}