In a PWA, I need to run some code after a successful API call (i.e., to remove some data from the localStorage).
fetch(API_URL, {
method: "POST",
body: JSON.stringify(data),
credentials: 'include',
headers: {
"Content-Type": "application/json",
"X-CSRF-TOKEN": CSRFToken
}
})
.then((response) => response.json())
.then((data) => {
if(data.success === 1){
// ---> code to be run after a successful API call <---
}
})
The Service Worker is generated by the vite-pwa-plugin
. This is the relevant portion of the configuration in vite.config.js
:
workbox: {
//...
runtimeCaching: [
{
urlPattern: /^API_URL/,
method: 'POST',
handler: 'NetworkOnly',
options: {
backgroundSync: {
name: 'work-queue',
options: {
maxRetentionTime: 24 * 60, // Retry for max of 24 Hours (specified in minutes)
},
}
},
}
]
}
If the app is offline, the API call is cached and correctly replayed when the app is back online, but when the call is replayed the code in the success block is not run.
Is there a way to add a callback in order to run code after a successful replay? If not directly using the plugin configuration, how can I achieve this result?