<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.
I have created a simple todo list as follows. `
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.