test
2 months ago
useAbilities.js
1 week ago
useCompleteOnboarding.js
2 months ago
useDateRangePicker.js
3 months ago
useEmail.ts
3 months ago
useEngagementChartData.js
3 months ago
useLicenseSettings.js
3 months ago
useLink.js
3 months ago
useMcpAdapterInstall.js
1 week ago
useMediaDetail.js
3 months ago
useMediaLibrary.js
3 months ago
useMediaList.ts
3 months ago
usePerformanceSettings.js
3 months ago
useRegisterActivePage.js
3 months ago
useSettingOption.js
1 week ago
useSimpleSettingsPage.js
1 week ago
useTopPerforming.js
3 months ago
useTopVideosPaginated.js
3 months ago
useUpgradeCTA.js
3 months ago
useUserDetail.js
3 months ago
useAbilities.js
54 lines
| 1 | import { useEffect, useState } from 'react'; |
| 2 | import apiFetch from '@wordpress/api-fetch'; |
| 3 | |
| 4 | /** |
| 5 | * Fetches the registered abilities catalog from the read-only REST endpoint. |
| 6 | * Only runs when AI access is enabled (no point fetching when the feature is off). |
| 7 | * |
| 8 | * @param {boolean} enabled Whether AI access is on. |
| 9 | * @return {{abilities: Array, counts: Object, loading: boolean, error: any}} State. |
| 10 | */ |
| 11 | const useAbilities = ( enabled ) => { |
| 12 | const [ abilities, setAbilities ] = useState( [] ); |
| 13 | const [ counts, setCounts ] = useState( { total: 0, free: 0, pro: 0 } ); |
| 14 | const [ loading, setLoading ] = useState( false ); |
| 15 | const [ error, setError ] = useState( null ); |
| 16 | |
| 17 | useEffect( () => { |
| 18 | if ( ! enabled ) { |
| 19 | return undefined; |
| 20 | } |
| 21 | |
| 22 | let active = true; |
| 23 | setLoading( true ); |
| 24 | setError( null ); |
| 25 | |
| 26 | apiFetch( { path: '/presto-player/v1/abilities' } ) |
| 27 | .then( ( res ) => { |
| 28 | if ( ! active ) { |
| 29 | return; |
| 30 | } |
| 31 | setAbilities( Array.isArray( res?.abilities ) ? res.abilities : [] ); |
| 32 | setCounts( res?.counts || { total: 0, free: 0, pro: 0 } ); |
| 33 | } ) |
| 34 | .catch( ( err ) => { |
| 35 | if ( active ) { |
| 36 | setError( err ); |
| 37 | } |
| 38 | } ) |
| 39 | .finally( () => { |
| 40 | if ( active ) { |
| 41 | setLoading( false ); |
| 42 | } |
| 43 | } ); |
| 44 | |
| 45 | return () => { |
| 46 | active = false; |
| 47 | }; |
| 48 | }, [ enabled ] ); |
| 49 | |
| 50 | return { abilities, counts, loading, error }; |
| 51 | }; |
| 52 | |
| 53 | export default useAbilities; |
| 54 |