diff --git a/src/edit.js b/src/edit.js index e062798..b661f5c 100644 --- a/src/edit.js +++ b/src/edit.js @@ -13,6 +13,7 @@ import { store as blockEditorStore, } from '@wordpress/block-editor'; import { useSelect, useDispatch } from '@wordpress/data'; +import apiFetch from '@wordpress/api-fetch'; import { AppleMapEdit } from './components/AppleMap'; import EditAuthForm from './components/EditAuthForm'; @@ -75,6 +76,28 @@ export default function MapsBlockAppleEdit(props) { const { updateAuthenticationStatus } = useDispatch(mapsBlockAppleStore); const { toggleSelection } = useDispatch(blockEditorStore); + /** + * Check if the credentials exist. + */ + const checkCredentials = async () => { + try { + const response = await apiFetch({ + path: 'MapsBlockApple/v1/GetJWT', + }); + if (response) { + return true; + } + + setIsLoading(false); + updateAuthenticationStatus(false); + return false; + } catch (error) { + setIsLoading(false); + updateAuthenticationStatus(false); + return false; + } + }; + /** * setup the initial authentication of mapkit and setup all the event listeners * @@ -144,8 +167,11 @@ export default function MapsBlockAppleEdit(props) { /** * handleMapkitReInitialization */ - const InitializeMapkit = () => { - AppleMapEdit.authenticateMap(localMapkit); + const InitializeMapkit = async () => { + const hasValidCredentials = await checkCredentials(); + if (hasValidCredentials) { + AppleMapEdit.authenticateMap(localMapkit); + } }; localMapkit.addEventListener('reinitialize', InitializeMapkit);