Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const state = {
- user: null,
- loading: false
- }
- const getters = {
- user: state => state.user,
- loading: state => state.loading
- }
- const actions = {
- me : ({ commit }) => {
- commit('setLoading', true)
- apolloClient
- .query({
- query: GET_CURRENT_USER
- })
- .then(({ data }) => {
- setTimeout(() => {
- commit('setLoading', false)
- // Add user data to state
- commit('setUser', data.me)
- console.log(data)
- }, 500)
- })
- .catch(err => {
- commit('setLoading', false)
- console.log(err)
- })
- },
- login: ({ commit }, payload) => {
- localStorage.setItem('token', '')
- apolloClient
- .mutate({
- mutation: LOGIN,
- variables: payload
- })
- .then(({ data }) => {
- setTimeout(() => {
- localStorage.setItem("token", data.login.auth.token)
- router.go('/')
- VueNotifications.success({ message: 'Welcome !' })
- }, 500)
- })
- .catch(err => {
- VueNotifications.error({ message: 'Error' });
- })
- },
- logout : async ({ commit }) => {
- Nprogress.start();
- // clear user in state
- commit('clearUser')
- // remove token in localStorage
- localStorage.setItem('token', '')
- // end session
- await apolloClient.resetStore()
- // redirect to home - kick users out of private pages
- router.push('/session/login')
- Nprogress.done();
- }
- }
- const mutations = {
- setUser: (state, payload) => {
- state.user = payload
- },
- setLoading: (state, payload) => {
- state.loading = payload
- },
- clearUser: state => (state.user = null)
- }
- computed: {
- ...mapGetters(['loading', 'user'])
- },
- created() {
- this.$store.dispatch('me')
- },
- watch: {
- deep: true,
- immediate:true,
- user(value) {
- if(value) {
- this.$router.push('/')
- }
- }
- },
- methods: {
- loginUser() {
- if(this.$refs.form.validate()) {
- this.$store.dispatch("login", {
- email: this.email,
- password: this.password
- })
- }
- }
- }
- router.beforeEach((to, from, next) => {
- if (to.matched.some(record => record.meta.requiresAuth)) {
- // this route requires auth, check if logged in
- // if not, redirect to login page.
- if (!store.getters.user) {
- next({
- path: '/session/login',
- })
- } else {
- next()
- }
- } else {
- next() // make sure to always call next()!
- }
- })
Add Comment
Please, Sign In to add comment