| 1 |
import { campaignsApi } from '../campaigns/campaignsApi'; |
| 2 |
import { |
| 3 |
applyCountdownDesign, |
| 4 |
updateBadge, |
| 5 |
updateCartPage, |
| 6 |
updateCountdown, |
| 7 |
updateTable, |
| 8 |
updateTextHighlight, |
| 9 |
} from '../discount/discountSlice'; |
| 10 |
|
| 11 |
import { setSaveStatus } from '../interaction/interactionSlice'; |
| 12 |
|
| 13 |
let abortController = null; |
| 14 |
let debounceTimer = null; |
| 15 |
|
| 16 |
const designAutoSaveMiddleware = (store) => (next) => async (action) => { |
| 17 |
const designActions = [ |
| 18 |
applyCountdownDesign.type, |
| 19 |
updateBadge.type, |
| 20 |
updateTextHighlight.type, |
| 21 |
updateCountdown.type, |
| 22 |
updateTable.type, |
| 23 |
updateCartPage.type, |
| 24 |
]; |
| 25 |
|
| 26 |
const result = next(action); |
| 27 |
const state = store.getState().discount; |
| 28 |
|
| 29 |
// 🔹 WHEN SAVE REQUEST SUCCESSFULLY COMPLETED |
| 30 |
if (campaignsApi.endpoints.patchCampaign.matchFulfilled(action)) { |
| 31 |
store.dispatch(setSaveStatus('success')); |
| 32 |
} |
| 33 |
|
| 34 |
// Auto-save only on design tab |
| 35 |
if (!designActions.includes(action.type) || state.ui[0] !== 1) { |
| 36 |
return result; |
| 37 |
} |
| 38 |
|
| 39 |
// Debounce |
| 40 |
if (debounceTimer) clearTimeout(debounceTimer); |
| 41 |
|
| 42 |
debounceTimer = setTimeout(() => { |
| 43 |
// Abort previous pending request |
| 44 |
if (abortController) { |
| 45 |
abortController.abort(); |
| 46 |
} |
| 47 |
|
| 48 |
abortController = new AbortController(); |
| 49 |
const signal = abortController.signal; |
| 50 |
|
| 51 |
// Read fresh state at fire time, not at dispatch time |
| 52 |
const freshState = store.getState().discount; |
| 53 |
|
| 54 |
//Before saving, set status = "saving" |
| 55 |
store.dispatch(setSaveStatus('saving')); |
| 56 |
|
| 57 |
// Send mutation request |
| 58 |
store.dispatch( |
| 59 |
campaignsApi.endpoints.patchCampaign.initiate( |
| 60 |
{ |
| 61 |
id: freshState.id, |
| 62 |
data: { design_blocks: freshState.design_blocks }, |
| 63 |
}, |
| 64 |
{ signal } |
| 65 |
) |
| 66 |
); |
| 67 |
}, 3000); |
| 68 |
|
| 69 |
return result; |
| 70 |
}; |
| 71 |
|
| 72 |
export default designAutoSaveMiddleware; |
| 73 |
|