Passing OAuth token from one Vuejs component to another

Viewed 517

I get OAuth token after successful OAuth login in a SuccessOAuth.vue component. I get the token details as follows:

           checkforTokens(){
             const queryString = this.$route.query;
             console.log(queryString);
             const token = this.$route.query.accessToken
             console.log(token);
             const secret = this.$route.query.tokenSecret
             console.log(secret);
             this.tokens.token = token;
             this.tokens.secret = secret;
          }
       },
       beforeMount() {
           this.checkforTokens();
       }

Now I want to use this token in another component apiCalls.vue where I use this token details to use call the API methods.

<script>
...
 methods:{

      getProductDetails() {
      console.log("==========================================");
      console.log(".. Get Product details....");
      axios
        .get("/auth/getShpDetails", {
          params: {
            token: this.tokens.token
          }
        })
        .then(response => {
          const productInfo = response.data;
          console.log("Product info :" + productInfo);
        });
    },

}
</script>

How do I pass the token details from SuccessOAuth component to apiCalls. I tried using props method but I wasn't able to get the token value to the script tag, not sure about other methods used to pass i.e using $emit and using vuex. Please suggest the best way and the right solution for the problem.

3 Answers

One way to do this could be vuex

in the root, store create a token field and make one getter that you can call from any vue component and on any life cycle hook..

The second way can be that you set the token to localStorage and get/use it wherever you need it

I would prefer the vuex method that way it ensures a single source of truth...

Here is how to use vuex store

  1. First of all install vuex depending on the vue version you are using, Generally, for the vue3 it is advisable to use npm i vuex@next

  2. Create a Store folder inside your src folder and in there add the index.js with the following code

import { createStore } from "vuex";
import axios from "axios"; // I Use axios for making API CALLS hence this pkg 

const store = createStore({
  state() {
    return {
      token: null,
    };
  },
});
export default store;

This is the basic store and state of you app for now.

  1. Lets start adding Actions first because actions are the async code used for making the API call and get the data from server
actions: {
    async login(context, payload) {
      try {
        const result = await axios({
          method: "POST",
          url: "auth/login",
          data: {
            email: payload.email,
            password: payload.password,
          },
        });

        //If the Request Successed with Status 200
        if (result.status === 200) {
          //A: Extract the Token
          const token = result.data.token;
          //B. Token to LocalStorage Optional if you wish to set it to localstorgae
          localStorage.setItem("token", token);
          //c: UPDATE THE STATE by calling mutation
          context.commit("setToken", {
            token,
          });
        }
      } catch (err) {
        console.log(err);
      }
    },
  },
  1. Next step as you might have guessed adding mutation, which is used for updating your app state..
mutations: {
    setToken(state, token) {
      state.token = token;
    },
  },
  1. Last the getter which you shall use to fetch the data either as computed inside your app components this is the
  getters: {
    getToken(state) {
      return state.token;
    },
  },

Finally after all of this you index.js should look something like this

import { createStore } from "vuex";
import axios from "axios";

const store = createStore({
  state() {
    return {
      token: null,
    };
  },
  actions: {
    async login(context, payload) {
      try {
        const result = await axios({
          method: "POST",
          url: "auth/login",
          data: {
            email: payload.email,
            password: payload.password,
          },
        });

        //If the Request Successed with Status 200
        if (result.status === 200) {
          //A: Extract the Token
          const token = result.data.token;
          //B. Token to LocalStorage Optional if you wish to set it to localstorgae
          localStorage.setItem("token", token);
          //c: UPDATE THE STATE by calling mutation
          context.commit("setToken", {
            token,
          });
        }
      } catch (err) {
        console.log(err);
      }
    },
  },
  mutations: {
    setToken(state, token) {
      state.token = token;
    },
  },
  getters: {
    getToken(state) {
      return state.token;
    },
  },
});

export default store;

NOTE - This is a General representation of how the code for vuex should looks like there are a ton of other way to achive the same result, depending on you project requirment The above code is not a final code, as it will need to be adjusted as per your test/example/project requirement

You can keep your token inside Localstorage or cookies. And use as per your need. Here is the sample code for this:

const token = 'token'

export function getToken() {
  return localStorage.getItem(token)
}

export function setToken(tokenData) {
  return localStorage.setItem(token, tokenData)
}


export function removeToken() {
  return localStorage.removeItem(token)
}

you can use Vuex for state management. Here is an article

As suggested by @Nishant Sham, I am just modifying the action method in index.js as seen below:

import Vue from 'vue'
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
          token: ''
    },
    getters: {
      getToken(state){
        return state.token;
      }
    },
    mutations: {
        setToken(state, tokenValue){
          state.token = tokenValue;
        }
    },
    actions: {
      setToken({commit}, tokenValue){
        commit("setToken", tokenValue);
      }
    }
   });

In your vue component you call getters and setters as follows:

<script>
      //Set token value
      var token = "dwe123313e12";//random token value assigned
      this.$store.commit("setToken", token);

      .....

      //Get token value
      var getToken = this.$store.getters.getToken;
</script>
Related