Search code examples
vue.jsvue-cookies

How to import a utility function that sets cookies into multiple Vue components


I have several components that I need to check if the user logged on/has valid access token

I currently do check this inside a Vue component method using the contents of isLoggedOut function below. I am thinking that I might need to create an external js file and import this js everywhere that I need to check of credentials. So js function will look sthg like below. However this function also resets the cookies in the component. see this.$cookies. I don't think this is possible due to scoping.

So how can I import functions (like from a utility js file) that also changes this objects? Or is there a better way of what avoiding code duplication in Vue/check for log out in multiple components using same code

import axios from "axios";
function isLoggedOut() {
  axios.defaults.withCredentials = true;
  const isLoggedOut = True;
  const path = `/user_authentication/protected`;
  axios
    .get(path, { withCredentials: true })
    .then((response) => {
      message = response.data["user"];
      isLoggedOut = false;
      return isLoggedOut;
    })
    .catch((error) => {
      console.error(error);
      this.$cookies.remove("csrf_access_token");
      isLoggedOut = true;
      return isLoggedOut;
    });
}

Solution

    1. Create an index.ts file in a folder named utils and export the funtion isLoggedOut.
    2. Pass the Vue app to the function isLoggedOut as a prop and call the vue methods.
    import Vue from 'vue'
    import axios from "axios";
    
    export function isLoggedOut(app: Vue) {
      axios.defaults.withCredentials = true;
      const isLoggedOut = True;
      const path = `/user_authentication/protected`;
    
      axios
        .get(path, { withCredentials: true })
        .then((response) => {
          message = response.data["user"];
          isLoggedOut = false;
          return isLoggedOut;
        })
        .catch((error) => {
          console.error(error);
    
          app.$cookies.remove("csrf_access_token");
    
          isLoggedOut = true;
          return isLoggedOut;
        });
    }
    

    Component

    import { isLoggedOut } from '~/utils'
    
    export default {
      methods: {
        logOut() {
          // Passing the Vue app
          isLoggedOut(this)
        }
      }
    }