/
useArticlesFetch.js
77 lines (61 loc) · 1.85 KB
/
useArticlesFetch.js
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
72
73
74
75
76
77
import { useState, useEffect } from '@wordpress/element';
const { apiFetch } = wp;
const { addQueryArgs } = wp.url;
const fetchJson = async(url) => {
const response = await fetch(url);
return response.json();
};
export const useArticlesFetch = (attributes, postType, postId, baseUrl = null) => {
const { article_count, post_types, posts, tags, ignore_categories } = attributes;
const [totalPosts, setTotalPosts] = useState(null);
const [displayedPosts, setDisplayedPosts] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const loadPage = async (reset = false) => {
if (loading) {
return;
}
setLoading(true);
const prevPosts = reset ? [] : displayedPosts;
const args = {
article_count,
post_types,
posts,
tags,
ignore_categories,
offset: prevPosts.length,
};
if (postType === 'post') {
args.exclude_post_id = postId;
}
try {
const response = baseUrl
? await fetchJson(`${ baseUrl }/wp-json/${ addQueryArgs('planet4/v1/get-posts', args) }`)
: await apiFetch({ path: addQueryArgs('planet4/v1/get-posts', args) });
const newPosts = [...prevPosts, ...response.recent_posts];
setDisplayedPosts(newPosts);
if (response.total_posts !== undefined && response.total_posts !== totalPosts) {
setTotalPosts(response.total_posts);
}
} catch (e) {
console.log(e);
setError(e.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
setDisplayedPosts([]);
loadPage(true);
}, [ article_count, post_types, posts, tags, ignore_categories ]);
return {
posts: displayedPosts,
totalPosts,
loading,
error,
hasMorePages: totalPosts > displayedPosts.length,
loadNextPage: () => {
loadPage();
},
};
};