4

I develop a Vue js app with vuex and nuxt, have this storage:

import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'

Vue.use(Vuex)

export const state = () => ({
  authUser: null,
  sidebar: false
})

export const mutations = {
  toggleSidebar (state) {
    state.sidebar = !state.sidebar
  },
  SET_USER: function (state, user) {
    state.authUser = user
  }
}

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
  strict: debug,
  plugins: [createPersistedState({
    storage: {
      getItem: key => Cookies.get(key),
      setItem: (key, value) => Cookies.set(key, value, { expires: 3, secure: true }),
      removeItem: key => Cookies.remove(key)
    }
  })]
})

// Polyfill for window.fetch()
require('whatwg-fetch')

export const actions = {
  // nuxtServerInit is called by Nuxt.js before server-rendering every page
  async login ({ commit }, { username, password }) {
    try {
      // const { data } = await axios.post('/api/login', { username, password })
      var data = username
      console.log(data)
      commit('SET_USER', data)
    } catch (error) {
      if (error.response && error.response.status === 401) {
        throw new Error('Bad credentials')
      }
      throw error
    }
  },

  async logout ({ commit }) {
    await axios.post('/api/logout')
    commit('SET_USER', null)
  }
}

And the following template:

<template>
  <div>
    <h1>Super secret page, hello {{user}}</h1>
    <p>If you try to access this URL not connected, you will see the error page telling your that you are not connected.</p>
    <nuxt-link to="/">Back to the home page</nuxt-link>
  </div>
</template>

<script>
export default {
  computed: {
    user () {
      return store.state.count
    }
  },
  middleware: 'auth'
}
</script>

The problem is i lose all my storage data if i reopen the tab in browser or hit ctrl+f5 (so no cookie is actually created). Also i can't access the user name in my template, is there any other, "correct" way to access the storage?

HardLuck
  • 1,497
  • 1
  • 22
  • 43

2 Answers2

-1

The correct way of handling it is using nuxtServerInit action in your store. That way you will make sure that it will be called on server-side before rendering.

export const actions = {
 nuxtServerInit ({dispatch}, context) {
  // your logic
 }
}
Gonzoarte
  • 19
  • 3
-3

You can use localStorage to persist data, here the example

actions: {
  setData ({commit}, payload) {
    localStorage.setItem('data', payload)
    commit('setData')
  }
}

and if you wanna get that data, you can use this code: localStorage.getItem('data')

Moreover about localStorage, take a look this Window.localStorage - Web APIs | MDN

Jefry Dewangga
  • 819
  • 10
  • 24