2023-10-18 09:14:14 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { useState, createContext, useEffect } from '@wordpress/element';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import { SubscriptionsContextType } from './types';
|
|
|
|
import { Subscription } from '../components/my-subscriptions/types';
|
|
|
|
import { fetchSubscriptions } from '../utils/functions';
|
|
|
|
|
|
|
|
export const SubscriptionsContext = createContext< SubscriptionsContextType >( {
|
|
|
|
subscriptions: [],
|
|
|
|
setSubscriptions: () => {},
|
2023-10-27 04:08:27 +00:00
|
|
|
loadSubscriptions: () => new Promise( () => {} ),
|
2023-10-18 09:14:14 +00:00
|
|
|
isLoading: true,
|
|
|
|
setIsLoading: () => {},
|
|
|
|
} );
|
|
|
|
|
|
|
|
export function SubscriptionsContextProvider( props: {
|
|
|
|
children: JSX.Element;
|
|
|
|
} ): JSX.Element {
|
|
|
|
const [ subscriptions, setSubscriptions ] = useState<
|
|
|
|
Array< Subscription >
|
|
|
|
>( [] );
|
|
|
|
const [ isLoading, setIsLoading ] = useState( true );
|
|
|
|
|
|
|
|
const loadSubscriptions = ( toggleLoading?: boolean ) => {
|
|
|
|
if ( toggleLoading === true ) {
|
|
|
|
setIsLoading( true );
|
|
|
|
}
|
|
|
|
|
2023-10-27 04:08:27 +00:00
|
|
|
return fetchSubscriptions()
|
2023-10-18 09:14:14 +00:00
|
|
|
.then( ( subscriptionResponse ) => {
|
|
|
|
setSubscriptions( subscriptionResponse );
|
|
|
|
} )
|
|
|
|
.finally( () => {
|
|
|
|
if ( toggleLoading ) {
|
|
|
|
setIsLoading( false );
|
|
|
|
}
|
|
|
|
} );
|
|
|
|
};
|
2023-10-27 04:08:27 +00:00
|
|
|
useEffect( () => {
|
|
|
|
loadSubscriptions( true );
|
|
|
|
}, [] );
|
2023-10-18 09:14:14 +00:00
|
|
|
|
|
|
|
const contextValue = {
|
|
|
|
subscriptions,
|
|
|
|
setSubscriptions,
|
2023-11-06 08:35:43 +00:00
|
|
|
loadSubscriptions,
|
2023-10-18 09:14:14 +00:00
|
|
|
isLoading,
|
|
|
|
setIsLoading,
|
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
|
|
|
<SubscriptionsContext.Provider value={ contextValue }>
|
|
|
|
{ props.children }
|
|
|
|
</SubscriptionsContext.Provider>
|
|
|
|
);
|
|
|
|
}
|