import React from 'react'; import Link from './Link'; import { useHistory } from 'react-router'; import { LINKS_PER_PAGE } from '../constants'; import { useQuery, gql } from '@apollo/client'; export const FEED_QUERY = gql` query FeedQuery( $take: Int $skip: Int $orderBy: LinkOrderByInput ) { feed(take: $take, skip: $skip, orderBy: $orderBy) { links { id createdAt url description postedBy { id name } votes { id user { id } } } count } } `; const NEW_LINKS_SUBSCRIPTION = gql` subscription { newLink { id url description createdAt postedBy { id name } votes { id user { id } } } } `; const getQueryVariables = (isNewPage, page) => { const skip = isNewPage ? (page - 1) * LINKS_PER_PAGE : 0; const take = isNewPage ? LINKS_PER_PAGE : 100; const orderBy = { createdAt: 'desc' }; console.log(isNewPage, page, LINKS_PER_PAGE, skip, take, orderBy); return { take, skip, orderBy }; }; const LinkList = () => { const history = useHistory(); const isNewPage = history.location.pathname.includes( 'new' ); const pageIndexParams = history.location.pathname.split( '/' ); const page = parseInt( // pageIndexParams.length - 1 pageIndexParams[pageIndexParams.length - 1] ); const pageIndex = page ? (page - 1) * LINKS_PER_PAGE : 0; const { data, loading, error, subscribeToMore } = useQuery(FEED_QUERY, { variables: getQueryVariables(isNewPage, page) }); const getLinksToRender = (isNewPage, data) => { if (isNewPage) { return data.feed.links; } const rankedLinks = data.feed.links.slice(); rankedLinks.sort( (l1, l2) => l2.votes.length - l1.votes.length ); return rankedLinks; }; subscribeToMore({ document: NEW_LINKS_SUBSCRIPTION, updateQuery: (prev, { subscriptionData }) => { if (!subscriptionData.data) return prev; const newLink = subscriptionData.data.newLink; const exists = prev.feed.links.find( ({ id }) => id === newLink.id ); if (exists) return prev; return Object.assign({}, prev, { feed: { links: [newLink, ...prev.feed.links], count: prev.feed.links.length + 1, __typename: prev.feed.__typename } }); } }); return ( <> {loading &&

Loading...

} {error &&
{JSON.stringify(error, null, 2)}
} {data && ( <> {getLinksToRender(isNewPage, data).map( (link, index) => ( ) )} {isNewPage && (
{ if (page > 1) { history.push(`/new/${page - 1}`); } }} > Previous
{ if ( page <= data.feed.count / LINKS_PER_PAGE ) { const nextPage = page + 1; history.push(`/new/${nextPage}`); } }} > Next
)} )} ); }; export default LinkList;