Struggling to make axios wait for an additional call in the interceptor to finish. Using NuxtJS as a frontend SPA with Laravel 8 API.
After trying various approaches for about 4 days, none seem to be effective.
TARGET
Require axios REQUEST interceptor to verify cookie existence. If cookie is missing, initial API call should fetch the cookie before proceeding with other requests.
APPROACH
Implemented Axios interceptor for requests that triggers a call to the cookie endpoint if cookie is absent.
Also caching the cookie request promise for multiple calls when cookie is still not retrieved.
ISSUE
Expected behavior was to first call the cookie API and then all subsequent endpoints but experiencing two different outcomes with the code provided:
A) Triggering extra cookie call but not in the expected sequence, resulting in multiple hits on Laravel endpoint without cookies leading to excessive sessions.
B) No calls being made at all (as shown in the example).
Confused about where I might be going wrong. Any insights?
export default function ({$axios, redirect, $cookiz, store}) {
$axios.onRequest(async request => {
const xsrfCookie = $cookiz.get('XSRF-TOKEN')
if (xsrfCookie === undefined || xsrfCookie === null || xsrfCookie === '') {
await store.dispatch('login/getXsrfCookie')
$axios.request(request)
}
$axios.request(request)
})
}
getXsrfCookie(context) {
if (context.state.xsrfCookiePromise instanceof Promise) {
return context.state.xsrfCookiePromise
}
const xsrfCookiePromise = this.$axios.get('/csrf-cookie').then(response => {
context.commit('setXsrfCookiePromise', null)
console.log('This is the cookie response', response)
})
context.commit('setXsrfCookiePromise', xsrfCookiePromise)
return context.state.xsrfCookiePromise
}