Skip to content
Permalink
Browse files

[Blog] Refactor to fetch blogposts into custom hooks

  • Loading branch information
yikkok-yong committed Oct 7, 2019
1 parent bd596dd commit 92062ac6564a1a8a3346b4f8e7807ed2d9567a2b
Showing with 85 additions and 42 deletions.
  1. +9 −42 pages/blog.jsx
  2. +76 −0 src/Hooks/useBlogPosts.js
@@ -34,6 +34,7 @@ import Header from "../src/Header/Header";
import Footer from "../src/Footer/Footer";
import PaginationBox from "../src/Components/PaginationBox";
import GoToTop from "../src/Components/GoToTop";
import useBlogPosts from "../src/Hooks/useBlogPosts";

const useStyles = makeStyles({
card: {
@@ -48,42 +49,10 @@ const useStyles = makeStyles({
});

function Blog() {
const [posts, setPosts] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [page, setPage] = useState(1);
const blogPost = useBlogPosts();
const [categories, setCategories] = useState([]);
const [selectedCategories, setSelectedCategories] = useState(new Set([]));
const [totalPages, setTotalPages] = useState(1);
const classes = useStyles();

useEffect(() => {
async function fetchPosts(blogPage, blogCategory) {
try {
setIsLoading(true);
const res = await fetch(
`https://blog.yikkok.com/wp-json/wp/v2/posts?_embed&page=${blogPage}&categories=${blogCategory}&per_page=5`,
{
method: "GET"
}
).then(response => {
setTotalPages(parseInt(response.headers.get("x-wp-totalpages"), 10));
return response.json();
});

if (res) {
setPosts([...res]);
setIsLoading(false);
}
} catch (error) {
// handling error
setIsLoading(false);
}
}

const selectedCategoriesArr = Array.from(selectedCategories).join(",");
fetchPosts(page, selectedCategoriesArr);
}, [page, selectedCategories]);

useEffect(() => {
async function fetchCategories() {
try {
@@ -104,29 +73,27 @@ function Blog() {
}, []);

function handleOnClickFetchPost(fetchPage: number) {
return () => setPage(fetchPage);
return () => blogPost.handleUpdatePage(fetchPage);
}

function handleOnChangeCategpry(id: number) {
return (event: Event, checked: boolean) => {
const clonedSelectedCategories = new Set(selectedCategories);
const clonedSelectedCategories = new Set(blogPost.selectedCategories);

if (!checked) {
clonedSelectedCategories.delete(id);
} else {
clonedSelectedCategories.add(id);
}

setPage(1);
setPosts([]);
setSelectedCategories(clonedSelectedCategories);
blogPost.handleUpdateSelectedCategories(clonedSelectedCategories);
};
}

return (
<>
<Header />
{isLoading ? <LinearProgress color="primary" /> : null}
{blogPost.loading ? <LinearProgress color="primary" /> : null}
<Container
style={{
display: "flex",
@@ -141,7 +108,7 @@ function Blog() {
</section>
<Grid container justify="space-around">
<Grid item xs={12} sm={8}>
{posts.map(post => (
{blogPost.posts.map(post => (
<Grid item xs={12} key={post.id}>
<Card className={classes.card}>
<CardHeader
@@ -210,12 +177,12 @@ function Blog() {
</Grid>
<Grid container justify="center" style={{ margin: "1.2rem 0" }}>
<Grid item xs={6}>
{new Array(totalPages).fill(0).map((val, index) => (
{new Array(blogPost.totalPages).fill(0).map((val, index) => (
<PaginationBox
page={index + 1}
// eslint-disable-next-line
key={index}
active={index + 1 === page}
active={index + 1 === blogPost.page}
onClick={handleOnClickFetchPost(index + 1)}
/>
))}
@@ -0,0 +1,76 @@
/**
* @file useBlogPosts
* @version 1.0.0
* @since 07 October 2019
* @description Custom React Hooks - fetch blog posts
*
* @flow
* @format
*/

import { useState, useEffect } from "react";

export default function useBlogPosts() {
const [posts, setPosts] = useState([]);
const [page, setPage] = useState(1);
const [selectedCategories, setSelectedCategories] = useState(
new Set<Array<Object>>([])
);
const [loading, setLoading] = useState();
const [error, setError] = useState();
const [totalPages, setTotalPages] = useState(1);

useEffect(() => {
async function fetchPosts(blogPage, blogCategory) {
try {
setLoading(true);
const res = await fetch(
`https://blog.yikkok.com/wp-json/wp/v2/posts?_embed&page=${blogPage}&categories=${blogCategory}&per_page=5`,
{
method: "GET"
}
).then(response => {
console.log(response.headers);

setTotalPages(parseInt(response.headers.get("x-wp-totalpages"), 10));
return response.json();
});

if (res) {
setPosts([...res]);
setLoading(false);
}
} catch (err) {
// handling error
setError(err.message);
setLoading(false);
}
}

const selectedCategoriesArr = Array.from(selectedCategories).join(",");
fetchPosts(page, selectedCategoriesArr);
}, [page, selectedCategories]);

function handleUpdateSelectedCategories(selecteds: any) {
const cloned = new Set<Array<Object>>(selecteds);

setPage(1);
setPosts([]);
setSelectedCategories(cloned);
}

function handleUpdatePage(pageNumber: number) {
setPage(pageNumber);
}

return {
loading,
handleUpdatePage,
handleUpdateSelectedCategories,
selectedCategories,
error,
page,
posts,
totalPages
};
}

0 comments on commit 92062ac

Please sign in to comment.
You can’t perform that action at this time.