Ujwal Pradhan
Ujwal Pradhan

Reputation: 45

How to getItems from localStorage saved by another process in Nuxt 3?

I have been trying to develop an application in Nuxt 3, and i am very new to this Meta-Framework. While a user logs in, the API sends token in response and it is saved to localStorage using if(process.client), however once the login is completed, i need my homepage to get the token stored in localstorage and now i am getting LocalStorage undefined error on build. Below is my code for setItems and getItems

code for setItems

methods: {
  async handleSubmit() {
    const response = await axios.post('http://localhost:8000/api/login', { email: this.email, password: this.password })

    console.log(response);
    notify({ title: response })

    if (process.client) {
      localStorage.setItem('token', response.data.token)
    }
    this.$router.push('/')
  }
}

getItems code

async created() {
  const response = await axios.get('http://localhost:8000/api/user', {
    headers: {
      Authorization: 'Bearer' +  localStorage.getItem('token')
    }
  })
  console.log(response)
},

Upvotes: 1

Views: 386

Answers (1)

kissu
kissu

Reputation: 46814

process.client should probably not be needed here, because handleSubmit will probably be called upon a click or a user interaction.

Meanwhile, you could use process.client in your second snippet because created lifecycle hook is ran on both server and client side. And there is no such thing as localStorage in Node.js.

Or you could use mounted, which is only called client-side.

Upvotes: 1

Related Questions