1

I need to save some usernames (input) and pictures (another button not shown in the code but the logic will be the same I think) in my Ionic 3 app without classic dataBase (think I'll use the base 64 for the pictures based on the camera from the device). Then I should retrieve them to create ion-card profile with it.

Actually everytime I run my loadUser() function it only retrieve me the last username but I would like to save more. Even when I go in the chrome DevTools/IndexedDB I can see only one key and value saved.

I need to persist theses key and value just like if is a database.

Using an input with NgModel and a 2 buttons (one to set data and one to get data) I am trying to save some username in my Ionic 3 app (without Sql Lite) but I see that the storage.set only accept string value. My idea was to use JSON.parse to retrieve the datas save in an array but the value is string at the begginning so if you have any idea let me know. Bellow is the code I tried but I get an error: "core.js:1449 ERROR Error: Uncaught (in promise): SyntaxError: Unexpected token d in JSON at position 0 SyntaxError: Unexpected token d in JSON at position 0 at JSON.parse ()"

PS: If it is not clear enough to you feel free to ask I am around for a while. Here is my code:

parameter.ts

export class ParametrePage {

   key: string = 'username';

   inputext: string;

   inputextGroup = [];

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private storage: Storage
 ) {}

  saveUser() {
  // set a key/value
     this.storage.set(this.key, this.inputext);
  }

  loadUser() {
// Or to get a key/value pair

  this.storage.get(this.key).then(val => {
  this.inputtextGroup = JSON.parse(val);
     console.log('You name is', val);
     });
    }
  }

parameter.html:

    <h6>Add a profilname</h6>
    <div class="form-container">
      <div class="input-container">
        <p class="diName">Name :</p>
        <ion-input [(ngModel)]="inputext" class="daInput" type="text"></ion- input>
        </div>

  <button class="charlotte-button addUser" ion-button icon-left 
  (click)="saveUser()">
      <ion-icon class="picto picto-reply"></ion-icon>
      Add a user
    </button>

    <button class="charlotte-button addUser" ion-button icon-left 
 (click)="loadUser()">
      <ion-icon class="picto picto-reply"></ion-icon>
      Load user
    </button>
5
  • Hey Emile, so your current code says that the key and the value are both strings (key:string, inputext: string). You should have no problem assigning the value you get without any JSON.parse. Commented Jun 15, 2018 at 13:41
  • so you are saying in your app you can have username1, username2, username3 and so on and you want to persist their names using ionic Storage? Commented Jun 15, 2018 at 14:35
  • @SergeyRudenko yes You right the users will save their username using input Commented Jun 15, 2018 at 14:39
  • I updated the answer but I think I am still unclear about your use case. We are talkng about client code here that is run at a particular user's machine. The persistence is "local" as well (Ionic Storage). So I hope you don't expect that this is a web service and that users can actually modify data together from their local clients? Commented Jun 15, 2018 at 14:47
  • No no it is just local (on the Ipad only) and there's any wheb service for this part of the app Commented Jun 15, 2018 at 14:48

1 Answer 1

1

In your case the value you store in the Storage is a string (inputext:string). JSON.parse will throw error if you attempt to parse a string as is. See more here: Why does JSON.parse("string") fail

Now based on your code you should not need JSON.parse at all:

loadUser() {
// Or to get a key/value pair
  this.storage.get(this.key).then(val => {
  this.inputtextGroup = val;
     console.log('You name is', val);
     });
  }
}

But if you say you data input eventually can be something else. Then you can condition it a bit with try catch:

loadUser() {
// Or to get a key/value pair
  this.storage.get(this.key).then(val => {
         try {
             JSON.parse(val);
         } catch(e) {
             // do here what you need since its a string
         }
             // do here what you need with parsed data
         });
    }
}

Now if there is a need to store more than one name at a time in the app. There are several "strategies" you can use:

  1. Differentiate stored data based on the "key". So the key (in key/value pair that you use to save data into Storage) should represent unique user, of course something needs to keep track of such users to be able to retrieve those:
users = ["userUniqueName1", "userUniqueName2", etc]
...
this.storage.get(users[1]).then(()=>{...})
  1. Store data in an object and stringify it before storing:
users = [ 
    { name: "userUniqueName1", surname: "whatever" },
    { name: "userUniqueName2", surname: "whatever" },
    ... 
]

now before you store the object (array), you need to stringify it:

storeUsers() {
    let usersStringifiedObj = JSON.stringify(this.users);
    this.storage.set("users", usersStringifiedObj);
}

retrieveUsers() {
    this.storage.get("users").then( users => {
        this.users = JSON.parse(users);
    })
}
Sign up to request clarification or add additional context in comments.

5 Comments

I think my question isn't clear enough I update my post
your code works but I need to save mutliple users to retrieve them later in the storage.get
thanks a lot I am trying that then I 'll let you know
I would suggest you describe in detail the outcome you want from your users perspectives as part of your question. Sort of dig into the problem you are solving without thinking of solution too much. This definitely helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.