|
| 1 | +import { useNotification, useFetchClient } from '@strapi/strapi/admin'; |
| 2 | +import { useIntl } from 'react-intl'; |
| 3 | +import { useEffect } from 'react'; |
| 4 | +import { useDispatch, useSelector } from 'react-redux'; |
| 5 | + |
| 6 | +import { RESOLVE_CONFIG } from '../constants'; |
| 7 | +import { PLUGIN_ID } from '../pluginId'; |
| 8 | +import { getTranslation } from '../utils/getTranslation'; |
| 9 | + |
| 10 | +const usePluginConfig = () => { |
| 11 | + const dispatch = useDispatch(); |
| 12 | + const { toggleNotification } = useNotification(); |
| 13 | + const { formatMessage } = useIntl(); |
| 14 | + const { isLoading, config } = useSelector((state: any) => state[`${PLUGIN_ID}_config`]); |
| 15 | + const client = useFetchClient(); |
| 16 | + |
| 17 | + useEffect(() => { |
| 18 | + // Do nothing if we have already loaded the config data. |
| 19 | + if (!isLoading && !!config) { |
| 20 | + return; |
| 21 | + } |
| 22 | + const abortController = new AbortController(); |
| 23 | + |
| 24 | + const fetchData = async () => { |
| 25 | + try { |
| 26 | + const endpoint = `/${PLUGIN_ID}/config`; |
| 27 | + const data = await client.get(endpoint, { |
| 28 | + signal: abortController.signal, |
| 29 | + }); |
| 30 | + |
| 31 | + return data ?? {}; |
| 32 | + } catch (err) { |
| 33 | + // eslint-disable-next-line no-console |
| 34 | + console.error(err); |
| 35 | + |
| 36 | + if (!abortController.signal.aborted) { |
| 37 | + toggleNotification({ |
| 38 | + type: 'warning', |
| 39 | + message: formatMessage({ |
| 40 | + id: getTranslation('notification.error'), |
| 41 | + defaultMessage: 'An error occurred while fetching data', |
| 42 | + }), |
| 43 | + }); |
| 44 | + |
| 45 | + return err; |
| 46 | + } |
| 47 | + return null; |
| 48 | + } |
| 49 | + }; |
| 50 | + fetchData().then((data) => dispatch({ type: RESOLVE_CONFIG, data })); |
| 51 | + |
| 52 | + // eslint-disable-next-line consistent-return |
| 53 | + return () => abortController.abort(); |
| 54 | + }, [client, config, dispatch, isLoading, toggleNotification, formatMessage]); |
| 55 | + |
| 56 | + return { config, isLoading }; |
| 57 | +}; |
| 58 | + |
| 59 | +export default usePluginConfig; |
0 commit comments