DEV Community

Discussion on: Vue and localStorage?

Collapse
 
michi profile image
Michael Z

Not sure if localStorage is truly what you want here as it is indeed local. So when you add an item on your PC, you won't be able to see it on your phone, etc.

Here's how a simple localStorage implementation could look like in this file: github.com/cguttweb/array-helper/b...

  1. Append localStorage to arrayMethods

Inside data() retrieve the added items (or default it to an empty array), then add it to arrayMethods

const addedMethods = JSON.parse(localStorage.getItem('addedMethods')) || []

// ...

return {
  // ...
 arrayMethods: [
    // ...,
    ...addedMethods,
  ]
}
  1. In addMethod(), set the localStorage:
const method = {
        name: this.newMethodName,
        method: this.newMethod,
        methodExample: this.newMethodExample
}
this.arrayMethods.push(method);

const addedMethods = localStorage.getItem('addedMethods') || []
addedMethods.push(method)
localStorage.setItem('addedMethods', JSON.stringify(addedMethods))
Collapse
 
cguttweb profile image
Chloe

Thanks for the reply I was attempting something similar but I think I just missed a step. I wasn't sure about LS if not LS then Vuex? Is there an alternative? I'm still pretty much a beginner to lot of this stuff so open to any suggestions.

Collapse
 
michi profile image
Michael Z • Edited

It really depends on your use case. But if you want to persist data so that, when one user adds a method, every person on the internet should see it too, then vuex won't help here either. It is just a way to manage your local state.

In such a case, what you actually want is to persist the data in a database like MySQL (requires server) or maybe something serverless like Firebase. Firebase is probably easier to set up as you don't need to host the database yourself somewhere and there is a free tier that should be good enough.

Thread Thread
 
cguttweb profile image
Chloe

I've read a bit on Firebase I will take a look and give it a go thanks :)