withStat.js
59 lines
| 1 | /** |
| 2 | * WordPress dependencies |
| 3 | */ |
| 4 | const { apiFetch } = wp; |
| 5 | const { useState } = wp.element; |
| 6 | const { createHigherOrderComponent } = wp.compose; |
| 7 | |
| 8 | /** |
| 9 | * Higher order component factory |
| 10 | * |
| 11 | * @return {Function} The higher order component. |
| 12 | */ |
| 13 | export default () => |
| 14 | createHigherOrderComponent( |
| 15 | (WrappedComponent) => (props) => { |
| 16 | const [loading, setLoading] = useState(false); |
| 17 | const [stat, setStat] = useState([]); |
| 18 | const [error, setError] = useState(""); |
| 19 | |
| 20 | // fetch data |
| 21 | // we could also abstract this function to make it reusable |
| 22 | // or do a higher order component |
| 23 | const fetchData = async ({ endpoint, params = {} }) => { |
| 24 | setLoading(true); |
| 25 | |
| 26 | let responseData; |
| 27 | try { |
| 28 | responseData = await apiFetch({ |
| 29 | path: wp.url.addQueryArgs(endpoint, { |
| 30 | ...params, |
| 31 | }), |
| 32 | }); |
| 33 | setStat(responseData); |
| 34 | } catch (e) { |
| 35 | console.error(e); |
| 36 | if (e?.message) { |
| 37 | setError(e.message); |
| 38 | } |
| 39 | } finally { |
| 40 | setLoading(false); |
| 41 | } |
| 42 | }; |
| 43 | |
| 44 | return ( |
| 45 | <WrappedComponent |
| 46 | loading={loading} |
| 47 | setLoading={setLoading} |
| 48 | fetchData={fetchData} |
| 49 | stat={stat} |
| 50 | setStat={setStat} |
| 51 | error={error} |
| 52 | setError={setError} |
| 53 | {...props} |
| 54 | /> |
| 55 | ); |
| 56 | }, |
| 57 | "withStat" |
| 58 | ); |
| 59 |