0
if (lastUserMessage === '/love') {
    const love = [];
    newlove = prompt("What do you love?", "Thing you love.");
    love.push(newlove);
    localStorage.setItem('love', JSON.stringify(love));
    botMessage = 'Awesome.';
}

if (lastUserMessage === 'What do I. love?') {
    var love2 =   JSON.parse(localStorage.getItem("love"));
    botMessage = love2;
}

Its suppose to store more than 1 object in the array, but I only get 1 value back.

4
  • This is not valid JavaScript, you can't have a newline in a string. Commented Jul 22, 2021 at 23:12
  • 2
    Where do you store more than one element in the array? const love = [] creates an empty array, then you do love.push(newlove). That's only one element. Commented Jul 22, 2021 at 23:13
  • 1
    You shouldn't do const love = [] every time you run this code. Do it once at the beginning of the script. Commented Jul 22, 2021 at 23:14
  • I did that and still only get one value. How do I add on and not just write over the current object. Commented Jul 22, 2021 at 23:18

1 Answer 1

1

Currently you always initialize your value to an empty array:

const love = [];

But it sounds like you expect it to retain the previously stored values in local storage. To do that, just initialize it to those values:

const love = JSON.parse(localStorage.getItem('love'));

As an extra step you might also do a null check on the stored array, just in case this is the first time the code was run and nothing is stored yet. Untested, but I suspect something like this may work:

const love = JSON.parse(localStorage.getItem('love') || '[]');

The idea being that getItem will return null if the item doesn't exist, so in that case you'd pass '[]' to JSON.parse and start with an empty array.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you david! That worked like a charm :)

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.