2

I am storing an array of objects in localStorage, retriving it each time, attachibg the new object and again storing.

the code works fine, only if there is already an entry in localStorage Following is the code:

var companies=[];

companies=JSON.parse(localStorage.getItem("companies")); //IMP line

companies.push(company);
localStorage.setItem("companies", JSON.stringify(companies));

This works fine, when I comment the 'IMP line' for first time, so that a record is inserted with single record. once the local storage contains a record with key "companies" everything goes fine.

please suggest a condition that can be checked while inserting the array first time. Thank You.

2 Answers 2

5

You need to check:

var strCompanies = localStorage.getItem("companies")
var companies = strCompanies ? JSON.parse(strCompanies) : [];
Sign up to request clarification or add additional context in comments.

Comments

1

localStorage.getItem will return null in case nothing found and so is JSON.parse(null). So you're ending up with companies being null.

Try this:

var companies=[];

if (localStorage.getItem("companies"))
    companies=JSON.parse(localStorage.getItem("companies")); //IMP line

companies.push(company);

localStorage.setItem("companies", JSON.stringify(companies));

See MDN

1 Comment

Thank you for explaination.. I was unaware that getItem returns null. now its simple:)

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.