tosanoob's picture
update a lot
0d37b12
raw
history blame
2.39 kB
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;