Can not get manually generate id with localStorage

Viewed 253

I have a data object of form-field data where id key has empty string as the initial value. I am trying to generate ids for every submitted form data and save in browser's storage. That, data.id = generateEmployeeId(); is written below:

function generateEmployeeId() {
    if (localStorage.getItem(KEYS.employeeId === null)) {
        localStorage.setItem(KEYS.employeeId, '0');
    }
    // eslint-disable-next-line radix
    let id = parseInt(localStorage.getItem(KEYS.employeeId));
    localStorage.setItem(KEYS.employeeId, (id += 1).toString());
    return id;
}

But unfortunately when I execute this code I get NaN

Note: Here, KEYS is an object of employeeId key of value employeeId

2 Answers

Your If statement condition is wrong. Your are saying localStorage.getItem(KEYS.employeeId === null) which is the equivalent to localStorage.getItem(false). the return value of localStorage.getItem(KEYS.employeeId === null) is null and parseInt(null) is NaN. SO in order for your code to work just change the condition in the if statement to localStorage.getItem(KEYS.employeeId) === null

    function generateEmployeeId() {
    if (localStorage.getItem(KEYS.employeeId) === null)
        localStorage.setItem(KEYS.employeeId, 0);

    let id = localStorage.getItem(KEYS.employeeId);
    localStorage.setItem(KEYS.employeeId, ++id);
    return id;
    }

Firstly, you will probably to change the first if statement as if you leave it like that it'd be like trying to retrieve a boolean from localStorage. As KEYS.employeeId === null will return a bool value.

Then, if it's convenient for you, you could just save the id as integers without needing to parseInt() and toString().

function generateEmployeeId() {
    if (localStorage.getItem(KEYS.employeeId) === null)
        localStorage.setItem(KEYS.employeeId, 0);

    let id = localStorage.getItem(KEYS.employeeId);
    localStorage.setItem(KEYS.employeeId, ++id);
    return id;
}
Related