view.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 'use client';
  2. import './style.scss';
  3. import { useState, useEffect } from 'react';
  4. import { fetchApi, throwError, getDateTime } from '@/lib/utils/client';
  5. import type { NewsArticlesResponse } from '@/types/response/news';
  6. import Loading from '@/app/component/Loading';
  7. import Pagination from '@/app/component/Pagination';
  8. function stripHtml(html: string | null): string {
  9. if (!html) {
  10. return '';
  11. }
  12. const doc = new DOMParser().parseFromString(html, 'text/html');
  13. return doc.body.textContent || '';
  14. }
  15. export default function View() {
  16. const [error, setError] = useState<string>('');
  17. const [loading, setLoading] = useState<boolean>(true);
  18. const [page, setPage] = useState<number>(1);
  19. const [data, setData] = useState<NewsArticlesResponse>({
  20. total: 0,
  21. list: []
  22. });
  23. useEffect(() => {
  24. if (error) {
  25. alert(error);
  26. setError('');
  27. }
  28. }, [error]);
  29. useEffect(() => {
  30. setLoading(true);
  31. fetchApi<NewsArticlesResponse>(`/api/news/articles?page=${page}&perPage=20`).then((res) => {
  32. throwError(res);
  33. setData(res.data!);
  34. }).catch(err => {
  35. setError(err.message);
  36. }).finally(() => {
  37. setLoading(false);
  38. });
  39. }, [page]);
  40. return (
  41. <section id='news'>
  42. { loading && <Loading /> }
  43. <p>NEWS</p>
  44. <hr />
  45. {data.list.length > 0 ? (
  46. data.list.map((row) => (
  47. <div key={row.id}>
  48. <article>
  49. <div>
  50. <img
  51. src={row.imageUrl || '/resources/no-image.png'}
  52. alt={row.title}
  53. onError={(e) => { (e.target as HTMLImageElement).src = '/resources/no-image.png'; }}
  54. />
  55. </div>
  56. <div>
  57. <a href={row.link || '#'} target='_blank' rel='noopener noreferrer'>
  58. {row.title}
  59. </a>
  60. <span>
  61. {/*<em>{row.sourceName || row.feedSourceName}</em>*/}
  62. {getDateTime(row.publishedAt)}
  63. </span>
  64. </div>
  65. <div className='desc'>
  66. {stripHtml(row.description)}
  67. </div>
  68. </article>
  69. <hr />
  70. </div>
  71. ))
  72. ) : (
  73. !loading && <p className='empty'>뉴스가 없습니다.</p>
  74. )}
  75. <br />
  76. {data.list.length > 0 && (
  77. <Pagination total={data.total} page={page} perPage={20} onChange={setPage} />
  78. )}
  79. </section>
  80. );
  81. }