Spaces:
Sleeping
Sleeping
File size: 2,385 Bytes
391b583 fdbdf19 391b583 fab48db fdbdf19 0d37b12 fdbdf19 0d37b12 fdbdf19 391b583 0dd6a66 fab48db fdbdf19 391b583 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
import { Container, Col, Row } from 'react-bootstrap';
import NewsItem from '../molecules/NewsItem';
import CacheStorage from './CacheStorage';
import axios from 'axios';
import { useState, useEffect } from 'react';
function NewsSection() {
const [feeds, setFeeds] = useState([]); // Lưu danh sách bài đăng
const [loading, setLoading] = useState(true); // Trạng thái tải dữ liệu
function truncateText(text, maxLength = 100) {
if (text.length <= maxLength) {
return text;
}
return text.slice(0, maxLength) + '...';
}
useEffect(() => {
const fetchFeeds = async () => {
try {
const response = await axios.get(process.env.REACT_APP_API_URL + '/feeds?limit=3');
setFeeds(response.data.data);
setLoading(false);
CacheStorage.set('feeds',JSON.stringify(response.data.data));
console.log(response.data);
} catch (error) {
console.error('Error fetching branches:', error);
setLoading(false);
}
}
if (CacheStorage.get('feeds')) {
setFeeds(JSON.parse(CacheStorage.get('feeds')));
setLoading(false);
console.log(JSON.parse(CacheStorage.get('feeds')));
console.log('fetched from cache');
} else {
fetchFeeds();
}
}, []);
let feedContent;
if (loading) {
feedContent = (<p>Đang tải các bài đăng...</p>);
} else {
feedContent = (<Row xs={1} md={2} xl={3} className="g-4">
{Array.from(feeds).map((feed, idx) => (
<Col key={idx}>
<NewsItem title={feed.title}
text={truncateText(feed.description)}
imageSrc={feed.image_url}
// feedHref={feed.feedHref}
feedHref={'/news?id='+feed.id} //demo
>
</NewsItem>
</Col>
))}
</Row>);
}
return (
<Container fluid id="news" className="text-center justify-content-center align-items-center my-5" style={{maxWidth:"90%"}}>
<h1 className='mb-5'>Tin tức</h1>
{feedContent}
</Container>
);
}
export default NewsSection; |