curiousroamers/src/client/Blog.tsx

71 lines
1.8 KiB
TypeScript

import React, {useState, useEffect, useCallback} from 'react';
import Display from './Display';
import Loader from './Loader';
import axios from 'axios';
/**
* @return {jsx} The homepage component
*/
export default function Blog() {
const [articles, setArticles]: any = useState([]);
const [page, setPage] = useState(0);
/**
* Check if you've reach the bottom of an HTMLElement
* @param {HTMLElement} element the element to check
* @return {boolean} true if reached else false
*/
function isBottom(element: HTMLElement) {
return element.getBoundingClientRect().bottom <= window.innerHeight;
}
const trackScrolling = useCallback(() => {
const element = document.getElementById('root')!;
if (isBottom(element)) {
setPage(page + 1);
}
}, []);
useEffect(() => {
const tmpArticles = articles;
tmpArticles.push(<Loader />);
setArticles(tmpArticles);
axios.get('/api/articles/' + page).then((res) => {
tmpArticles.pop();
for (let i = 0; i < res.data.length; i++) {
tmpArticles.push(<h1>{res.data[i].title}</h1>);
tmpArticles.push(<small>
{new Date(res.data[i].createdAt).toLocaleDateString()}
</small>);
tmpArticles.push(<br/>);
for (let j = 0; j < res.data[i].tags.length; j++) {
tmpArticles.push(<small>
{res.data[i].tags[j].name} </small>);
}
tmpArticles.push(<div
dangerouslySetInnerHTML=
{{__html: res.data[i].sanitizedHtml}}></div>);
}
console.log('test');
setArticles([...tmpArticles]);
console.log(articles);
});
}, [page]);
useEffect(() => {
window.addEventListener('scroll', trackScrolling);
return () => {
window.removeEventListener('scroll', trackScrolling);
};
}, [trackScrolling]);
return (
<React.Fragment>
<Display text='Carnet de voyage' />
<div className='container'>
{articles}
</div>
</React.Fragment>
);
}