| 1 |
import { useEffect, useRef, useState } from 'react'; |
| 2 |
import { useDispatch } from 'react-redux'; |
| 3 |
import { useLocation, useSearchParams } from 'react-router'; |
| 4 |
import { useGetCampaignQuery } from '../features/campaigns/campaignsApi'; |
| 5 |
import { |
| 6 |
useGetBOGOTypesQuery, |
| 7 |
useGetDiscountBasedOnQuery, |
| 8 |
useGetDiscountIntentsQuery, |
| 9 |
useGetDiscountMethodsQuery, |
| 10 |
useGetDiscountTypesQuery, |
| 11 |
useGetFiltersQuery, |
| 12 |
useGetWhatGetsDiscountQuery, |
| 13 |
} from '../features/discount/discountApi'; |
| 14 |
import { editCampaign } from '../features/discount/discountSlice'; |
| 15 |
|
| 16 |
const useEditCampaign = () => { |
| 17 |
const [searchParams] = useSearchParams(); |
| 18 |
const [id, setId] = useState(''); |
| 19 |
const [skip, setSkip] = useState(true); |
| 20 |
const { data: campaign, isLoading } = useGetCampaignQuery(id, { skip }); |
| 21 |
const [uiLoading, setUiLoading] = useState(true); |
| 22 |
const dispatch = useDispatch(); |
| 23 |
const { isError, error } = useGetDiscountIntentsQuery(); |
| 24 |
const hasCampaignLoaded = useRef(false); |
| 25 |
|
| 26 |
// Trigger these queries to ensure data is loaded, if necessary |
| 27 |
useGetFiltersQuery(); |
| 28 |
useGetWhatGetsDiscountQuery(); |
| 29 |
useGetDiscountMethodsQuery(); |
| 30 |
useGetDiscountTypesQuery(); |
| 31 |
useGetDiscountBasedOnQuery(); |
| 32 |
useGetBOGOTypesQuery(); |
| 33 |
|
| 34 |
const { state } = useLocation(); |
| 35 |
|
| 36 |
useEffect(() => { |
| 37 |
if (searchParams.get('edit') && skip) { |
| 38 |
if (state) { |
| 39 |
dispatch(editCampaign(state)); |
| 40 |
hasCampaignLoaded.current = true; |
| 41 |
} else { |
| 42 |
setUiLoading(true); |
| 43 |
const id = searchParams.get('edit'); |
| 44 |
setId(id); |
| 45 |
setSkip(false); |
| 46 |
} |
| 47 |
} |
| 48 |
}, [searchParams, skip, state, dispatch]); |
| 49 |
|
| 50 |
useEffect(() => { |
| 51 |
if ( |
| 52 |
isError && |
| 53 |
error.status === 403 && |
| 54 |
error.data.code === 'rest_cookie_invalid_nonce' |
| 55 |
) { |
| 56 |
window.location.replace(DISCO.site_url + '/wp-login.php'); |
| 57 |
} |
| 58 |
}, [isError, error]); |
| 59 |
|
| 60 |
// Only dispatch editCampaign on initial load, not on refetches |
| 61 |
useEffect(() => { |
| 62 |
if (campaign && !hasCampaignLoaded.current) { |
| 63 |
dispatch(editCampaign(campaign)); |
| 64 |
hasCampaignLoaded.current = true; |
| 65 |
} |
| 66 |
setUiLoading(false); |
| 67 |
}, [campaign, dispatch]); |
| 68 |
|
| 69 |
return { |
| 70 |
isLoading: isLoading || uiLoading, |
| 71 |
}; |
| 72 |
}; |
| 73 |
|
| 74 |
export default useEditCampaign; |
| 75 |
|