bigbinary / wheel

Don't reinvent the wheel for every new Rails project. Use sane Defaults.

Home Page:https://wheel-production.neetodeployapp.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Return null if localStorage value is not found

Amaljith-K opened this issue · comments

const getFromLocalStorage = key => {
let response = "";
try {
const value = localStorage.getItem(key);
response = isPresent(value) ? JSON.parse(value) : "";
} catch (error) {
logger.error(error);
response = "";
}
return response;
};

Here we are returning an empty string if the localStorage value is not found.
Since we allow storing objects by serializing them as JSON into localStorage, the function caller is expecting an object.
Getting an empty string instead of an object would lead to undefined behavior and developers always needs to be watchful for edge cases like the following:

const fiber = { length: 0, type: "nylon" };
setToLocalStorage("fiber", fiber);

console.log(getFromLocalStorage("fiber").length); // we get length = 0 here from the value we have set

localStorage.clear();

console.log(getFromLocalStorage("fiber").length); // we still get length = 0, which is "".length

Make the utility function fail fast by returning null. That way, the above code fails when we have no value present in the storage.
@yedhink _a
Thanks @paulsojan for pointing this out.

Also make sure to propagate this change to our learning materials and granite.