I can't understand what is the error in this code

I can't understand why Firefox gives me error in line 31 saying that elencouser (that I declared on top of my code) is null, please help me if you can, thanks

var elencouser = [];
var array;

$(document).ready(function(){

    if (typeof(Storage) !== "undefined") {

        if(sessionStorage.getItem("arrayuser") == "undefined"){
            elencouser[0] = new utente("admin","admin","Danilo","Cerasi");
            array = JSON.stringify(elencouser);
            sessionStorage.setItem("arrayuser",array);
        }

        $("#registrati").click(function(){

            array = sessionStorage.getItem("arrayuser");
            elencouser = $.parseJSON(array);

            var email=$("#exampleInputEmail").val();        //prendo quello che ha scritto l'utente
            var password=$("#exampleInputPassword").val();
            var nome=$("#exampleFirstName").val();
            var cognome=$("#exampleLastName").val();

            elencouser.push( new utente(email,password,nome,cognome) );
            alert("sei appena stato registrato! Ora verrai reindirizzato alla pagina di login..");

            location.href="login.html";
        });

    }else{
        alert("riscontriamo problemi di apertura con il browser che stai utilizzando, aggiornalo oppure prova con uno doverso");    //se il browser non supporta il il session storage glielo dico
    }
});

Upvotes: 0

Views: 72

Answers (1)

Jonas D.
Jonas D.

Reputation: 371

The undefined check should use typeof to check against "undefined"

i.e.

if(typeof sessionStorage.getItem("arrayuser") == "undefined"){

Note that arrayuser might still contain different data due to various reasons (either by manual editing by the user, or by legacy code).

Thus I would always assume you might not get a valid array back when getting arrayuser from the local/session storage.

In your click event I would also check if arrayuser is valid, and if it's an array:

try {
    const arrayuser = sessionStorage.getItem("arrayuser");
    elencouser = JSON.parse(arrayuser);

    if(!Array.isArray(elencouser)) throw "arrayuser was not a valid array";
} catch(e) {
    console.error(e);
    elencouser = [];
}

Upvotes: 3

Related Questions