patrick-steele-idem / morphdom

Fast and lightweight DOM diffing/patching (no virtual DOM needed)
MIT License
3.21k stars 131 forks source link

Dom Elements are not Updated Correctly #180

Closed Jeraldy closed 4 years ago

Jeraldy commented 4 years ago

I have created a simple todo list as follows. `

<script src="morphdom-umd.js"></script>
<script>

    var state = {
        todos: [],
        value: ''
    }

    function setState(newState) {
        state = { ...state, ...newState }
        console.log(state)
        morphdom(node, render())
    }

    function removeTodo(v) {
        setState({
            todos: state.todos.filter(value => value != v)
        })
    }

    var input = document.createElement('input')
    input.value = state.value

    input.onkeyup = function (e) {
        setState({
            value: e.target.value
        })
    }

    var btn = document.createElement('button')
    btn.innerText = "Add Todo"
    btn.onclick = () => {
        setState({
            todos: [...state.todos, state.value],
            value: ''
        })    
    }

    var div = document.createElement('div')
    div.appendChild(input)
    div.appendChild(btn)

    var todoList = document.createElement('div')

    function todoItem(v) {
        var todo = document.createElement('div')
        var todoX = document.createElement('button')
        todo.innerText = v
        todoX.innerText = "Remove"
        todo.appendChild(todoX)
        todoX.onclick = () => removeTodo(v)
        return todo
    }

    function render() {
        var { todos } = this.state
        todos.forEach((v) => {
            todoList.appendChild(todoItem(v))
        })
        div.appendChild(todoList)
        return div
    }

    var node = render()
    document.getElementById("root").appendChild(node)

</script>`

When I click add Todo for the first time it works perfectly. Then Typing on the text box triggers addition of todos which should not happen. Removing of todos updates the state correctly but the dom isn't updated accordingly. Not sure if there is something wrong with my code.

Jeraldy commented 4 years ago

I have solved my issue. I realized that I was not clearing the do to list div before adding and re-rendering todos.