withDataList.js
83 lines
| 1 | /** |
| 2 | * WordPress dependencies |
| 3 | */ |
| 4 | const { __ } = wp.i18n; |
| 5 | const { apiFetch } = wp; |
| 6 | const { useState } = wp.element; |
| 7 | const { createHigherOrderComponent } = wp.compose; |
| 8 | |
| 9 | /** |
| 10 | * Higher order component factory |
| 11 | * |
| 12 | * @return {Function} The higher order component. |
| 13 | */ |
| 14 | export default () => |
| 15 | createHigherOrderComponent( |
| 16 | (WrappedComponent) => (props) => { |
| 17 | const [loading, setLoading] = useState(false); |
| 18 | const [page, setPage] = useState(1); |
| 19 | const [total, setTotal] = useState(0); |
| 20 | const [totalPages, setTotalPages] = useState(0); |
| 21 | const [data, setData] = useState([]); |
| 22 | const [error, setError] = useState(""); |
| 23 | |
| 24 | // fetch data |
| 25 | // we could also abstract this function to make it reusable |
| 26 | // or do a higher order component |
| 27 | const fetchData = async ({ endpoint, params = {} }) => { |
| 28 | setLoading(true); |
| 29 | |
| 30 | let responseData; |
| 31 | try { |
| 32 | responseData = await apiFetch({ |
| 33 | path: wp.url.addQueryArgs(endpoint, { |
| 34 | page, |
| 35 | per_page: 5, |
| 36 | ...params, |
| 37 | }), |
| 38 | parse: false, |
| 39 | }).then((res) => { |
| 40 | const total = res.headers |
| 41 | ? parseInt(res.headers.get("X-WP-Total")) |
| 42 | : 0; |
| 43 | const totalPages = res.headers |
| 44 | ? parseInt(res.headers.get("X-WP-TotalPages")) |
| 45 | : 0; |
| 46 | setTotal(total); |
| 47 | setTotalPages(totalPages); |
| 48 | return res.json(); |
| 49 | }); |
| 50 | |
| 51 | setData(responseData); |
| 52 | } catch (e) { |
| 53 | console.error(e); |
| 54 | if (e?.message) { |
| 55 | setError(e.message); |
| 56 | } |
| 57 | } finally { |
| 58 | setLoading(false); |
| 59 | } |
| 60 | }; |
| 61 | |
| 62 | return ( |
| 63 | <WrappedComponent |
| 64 | loading={loading} |
| 65 | setLoading={setLoading} |
| 66 | fetchData={fetchData} |
| 67 | page={page} |
| 68 | setPage={setPage} |
| 69 | total={total} |
| 70 | setTotal={setTotal} |
| 71 | totalPages={totalPages} |
| 72 | setTotalPages={setTotalPages} |
| 73 | data={data} |
| 74 | setData={setData} |
| 75 | error={error} |
| 76 | setError={setError} |
| 77 | {...props} |
| 78 | /> |
| 79 | ); |
| 80 | }, |
| 81 | "withDataList" |
| 82 | ); |
| 83 |