'use client' import React, {ReactElement, useEffect, useState} from 'react' import fetcher from '@/lib/fetcher' import useSWR from 'swr' import {Card} from '@/components/ui/Card' type Article = { slug: string authors: string title: string date: string description: string } type FetchArticlesResponse = { data: Article[] error: string isLoading: boolean } type ArticleNavProps = { slug: string } type PaginationProps = { next: Article | null prev: Article | null } function useFetchArticles() { const {data, error, isLoading} = useSWR(`/api/articles/`, fetcher) as FetchArticlesResponse return { articles: data, isLoading, isError: error } } export default function ArticleNav({slug}: ArticleNavProps): ReactElement | null { const {articles, isLoading, isError} = useFetchArticles() const [{next, prev}, setPagination] = useState({next: null, prev: null}) useEffect(() => { const findAdjacentArticles = (articles: Article[], slug: string) => { if (articles) { const index = articles.findIndex(article => article.slug === slug) const next = index > 0 ? articles[index - 1] : null const prev = index < articles.length - 1 ? articles[index + 1] : null setPagination({next, prev}) } } findAdjacentArticles(articles, slug) }, [articles, slug]) if (isError) return null return (
) }