Skip to main content

Posts

Showing posts with the label vue

JavaScript Closure Gotcha with Vuex

Closures in Javascript are not just an additional feature, they're inherent to the language. Every time a function is created, it's lexical scope is automatically captured in it's current state along with the function.  It can quickly get complex when using reactive paradigms, such as with frameworks like Vue , as happened with me today. Here's the code: async setSwaggerClient({ state, commit, rootState}) { ... let authToken = rootState.user.key; Swagger( '/api/swagger.json', { requestInterceptor: (req) => { req.headers["X-CSRFToken"] = g_csrftoken; if(authToken !== null) { req.headers["Authorization"] = `Token ${authToken}`; } return req; } } ) ... } The function setSwaggerClient is a Vuex action that creates and sets the swagger client in a Vuex store. During creation I pass a functi...