2025-02-17 08:38:06 +01:00
|
|
|
/**
|
2025-02-24 15:46:34 +01:00
|
|
|
* Hooks: Provide the main API for components to interact with the features store.
|
2025-02-17 08:38:06 +01:00
|
|
|
*
|
|
|
|
* These encapsulate store interactions, offering a consistent interface.
|
|
|
|
* Hooks simplify data access and manipulation for components.
|
|
|
|
*
|
|
|
|
* @file
|
|
|
|
*/
|
|
|
|
|
2025-02-24 15:46:34 +01:00
|
|
|
import { useSelect, useDispatch } from '@wordpress/data';
|
|
|
|
import { useEffect } from '@wordpress/element';
|
|
|
|
import apiFetch from '@wordpress/api-fetch';
|
|
|
|
import { STORE_NAME, REST_PATH } from './constants';
|
2025-02-17 08:38:06 +01:00
|
|
|
|
2025-02-24 15:46:34 +01:00
|
|
|
export const useFeatures = () => {
|
|
|
|
const { features, isReady } = useSelect( ( select ) => {
|
|
|
|
const store = select( STORE_NAME );
|
2025-02-17 08:38:06 +01:00
|
|
|
|
2025-02-24 15:46:34 +01:00
|
|
|
return {
|
|
|
|
features: store.getFeatures() || [],
|
|
|
|
isReady: select( STORE_NAME ).transientData()?.isReady || false,
|
|
|
|
};
|
|
|
|
}, [] );
|
2025-02-17 08:38:06 +01:00
|
|
|
|
2025-02-24 15:46:34 +01:00
|
|
|
const { setFeatures, setIsReady } = useDispatch( STORE_NAME );
|
2025-02-17 08:38:06 +01:00
|
|
|
|
2025-02-24 15:46:34 +01:00
|
|
|
useEffect( () => {
|
|
|
|
const loadInitialFeatures = async () => {
|
|
|
|
try {
|
|
|
|
const response = await apiFetch( { path: REST_PATH } );
|
2025-02-17 08:38:06 +01:00
|
|
|
|
2025-02-24 15:46:34 +01:00
|
|
|
if ( response?.data?.features ) {
|
|
|
|
const featuresData = response.data.features;
|
|
|
|
|
|
|
|
if ( featuresData.length > 0 ) {
|
|
|
|
await setFeatures( featuresData );
|
|
|
|
await setIsReady( true );
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch ( error ) {}
|
|
|
|
};
|
|
|
|
|
|
|
|
if ( ! isReady ) {
|
|
|
|
loadInitialFeatures();
|
|
|
|
}
|
|
|
|
}, [ isReady, setFeatures, setIsReady ] );
|
2025-02-17 08:38:06 +01:00
|
|
|
|
|
|
|
return {
|
|
|
|
features,
|
2025-02-24 15:46:34 +01:00
|
|
|
isReady,
|
|
|
|
fetchFeatures: async () => {
|
|
|
|
try {
|
|
|
|
const response = await apiFetch( { path: REST_PATH } );
|
|
|
|
const featuresData = response.data?.features || [];
|
|
|
|
|
|
|
|
if ( featuresData.length > 0 ) {
|
|
|
|
await setFeatures( featuresData );
|
|
|
|
await setIsReady( true );
|
|
|
|
return { success: true, features: featuresData };
|
|
|
|
}
|
|
|
|
return { success: false, features: [] };
|
|
|
|
} catch ( error ) {
|
|
|
|
return { success: false, error, message: error.message };
|
|
|
|
}
|
|
|
|
},
|
2025-02-17 08:38:06 +01:00
|
|
|
};
|
|
|
|
};
|