ewizard
ewizard

Reputation: 2862

create and store user objects using localstorage

I am trying to create a user database using localStorage. I just need to store the created user with a unique id so I can reference it as a key later. Right now I have this code in my application.js:

$(document).ready(function() {
    $("#signupform").submit(function(e) {
        e.preventDefault();
        var user = {
            name: $('#pname').val(),
            email: $('#email').val()
        };
        localStorage.setItem('user', JSON.stringify(user));
        console.log(JSON.parse(localStorage.getItem('user')).name);
        var html = new EJS({url: 'templates/usershow.ejs'}).render(user);
        var content = document.getElementById('content');
        content.innerHTML = content.innerHTML + html;
        $("#signupform").remove();   
    });
});

I need localStorage.setItem('user'... to be something like localStorage.setItem('i'... where "i" increments with each newly created user (like an index) when the submit button is clicked. Would it make more sense to use the user email as the key? That way I can look up each user by their email? How would I go about doing this? Again...I am just trying to set up a user database where I can easily reference users and their info using localStorage. Show me how!

Upvotes: 0

Views: 1413

Answers (2)

Nathan Bubna
Nathan Bubna

Reputation: 6933

It makes more sense to use the user's email. Simplicity is good.

BUT... this is localStorage. There shouldn't ever be more than one user using it, right? localStorage itself is unique to the client application. Are there really going to be multiple users using the same browser?

If so, then this is fine. But i wonder if you are really thinking about how localStorage works...

Upvotes: 1

Will
Will

Reputation: 151

I'd go about incrementing an ID by storing a nextUniqueId in localStorage, then grab that for the key and increment it. Something like this:

function getNextUnique () {
    var next = localStorage.getItem('nextUniqueId');
    next = next ? parseInt(next) : 0;
    var newNext = next + 1;
    localStorage.setItem('nextUniqueId', newNext);
    return next;
}

Call it whenever you want to save a new user:

localStorage.setItem(getNextUnique(), JSON.stringify(user));

Upvotes: 1

Related Questions