codeHysteria
codeHysteria

Reputation: 63

Storing items into local storage seems to not working

Im making todo app for myself. And trying to save the data inside the local storage. I just want to ask about my code if iam doing something wrong.

my html :
    <div id="todo1">
        <center><h1>All Tasks</h1></center>
        <div id="todo"></div>
        <form class="add-items">
            <center><input type="text" name="item" placeholder="eg. Buy bread" class="add_task" required></center>
        <center><input type="submit" class="add" value="add task"/></center>
        </form>

    </div>
my javascript:
    const addItems = document.querySelector('.add-items'); 
    const items = JSON.parse(localStorage.getItem('items')) || [];

    function addItem(e) {
        e.preventDefault();
        let todo = document.querySelector('#todo');
        let input = (this.querySelector('[name=item]').value);
        let text = document.createTextNode(input);
        let markup = `<center><div class="task">${input}<i class="far fa-check-circle"></i><i class="far fa-trash-alt" id="trash"></i></div></center>`;
        todo.insertAdjacentHTML('beforeend', markup);
        const item = {
            task:input
        };
        items.push(item);
        localStorage.setItem('items', JSON.stringify(items));
        this.reset();
    }

    addItems.addEventListener('submit', addItem);

Upvotes: 1

Views: 141

Answers (1)

Senthur Athiban
Senthur Athiban

Reputation: 146

Actually the Items that you stored into localStorage are not binded to the html dom initially that's why you are unable to see your items from localStorage in the view.

[http://jsfiddle.net/r76xots2/9/]

So here is the working link for your code with some optimization where I have created a common function that will update your dom from the localStorage which can be used every time whenever you want to update.

I have also created a check so the same item can't be inserted twice. If you don't require that, you could remove or comment it.

Upvotes: 1

Related Questions