0

I came to a point where I move really comfortable within Vanilla JS when it comes to Procedural programming, so I jumped into Functional programming to widen my knowledge and get ready for the next level of Javascript usage...

Well, it took like 3 minutes to get to my first unwanted encounter were saving to the local store not exactly working as I planned.

The app would simply add userInput.value to the local-storage when the button is clicked. What happens is it adds to the empty local-store. Fine. Then when the user tries to add again this is the result

.

Here is the full code, there is only one userInput.value and a button to trigger

//////////////////////////////////////////////////////
// Functional programmed version:
//////////////////////////////////////////////////////

function getStorageData() {
    return localStorage.getItem('itemsArray') || [];
}
function setStorageData(obj) {
    return localStorage.setItem('itemsArray', JSON.stringify(obj));
}

function getUserInput(input) {
    return document.querySelector(input).value;
}

function addToStorage(userInput) {
    return setStorageData({...getStorageData(), userInput});
}

function submitHandler(event) {
    event.preventDefault();
    addToStorage(getUserInput('input'));
}

function connectForm(button, submit) {
    const addBtn = document.querySelector(button);
    addBtn.addEventListener('click', submit);
}

connectForm('.add-btn', submitHandler)

A problem I see the app tries to put it as an object like {userInput: value} instead just value so it probably breaking on adding the same object with a different value... How can I get rid of the variable here? It seemingly puts the variable there automatically.

Thanks for all help in advance!

mplungjan
  • 155,085
  • 27
  • 166
  • 222

1 Answers1

1

Here's what you need to do ..

function getStorageData() {
    return JSON.parse(localStorage.getItem('itemsArray') || '[]'); // load the array filled or empty
}

function setStorageData(obj) {
    localStorage.setItem('itemsArray', JSON.stringify(obj)); // nothing to return here
}

function getUserInput(input) {
    return document.querySelector(input).value; // this return purely a value and not a JSON object.
}

function addToStorage(userInput) {
    setStorageData([...getStorageData(), userInput]); // you are changing an array into a JSON object here, and also nothing to return here.
}

others are fine.

HymnZzy
  • 2,482
  • 1
  • 13
  • 26
  • In the meantime, I managed to solve and finish the list as a whole. addToStorage iterate into an array instead of an object was an issue, the other one was ```getStorageData() { return JSON.parse(localStorage.getItem('itemsArray')) || '[]'; }``` Only local storage should be parsed. – Krisztian Nagy Dec 23 '20 at 23:52
  • No. If `localStorage` is not set, you'll get a JSON.parse error. – HymnZzy Dec 24 '20 at 02:44