Created
March 10, 2021 06:42
-
-
Save jaylandro/2fe6bd057a6535a53c5381af945ab31b to your computer and use it in GitHub Desktop.
Super minimal state w/ proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.subscribers = []; | |
const defaultState = { | |
todos: [] | |
}; | |
const state = new Proxy(defaultState, { | |
set(state, key, value) { | |
const oldState = { ...state }; | |
state[key] = value; | |
window.subscribers.forEach((callback) => callback(state, oldState)); | |
return state; | |
} | |
}); | |
function addTodo() { | |
event.preventDefault(); | |
const todoForm = document.getElementById("todo-form"); | |
const formData = new FormData(todoForm); | |
const todo = formData.get("todo-text"); | |
todoForm.reset(); | |
state.todos = [...state.todos, todo]; | |
} | |
function renderTodos(currentState, oldState = null) { | |
const todoList = document.getElementById("list"); | |
if (oldState && oldState.todos === currentState.todos) { | |
return; | |
} | |
todoList.innerHTML = state.todos | |
.map( | |
(todo, i) => `<li> | |
<input type="checkbox" id="a${i}" value="done"> | |
<label for="a${i}">${todo}</label> | |
</li>` | |
) | |
.join(""); | |
} | |
window.subscribers.push(renderTodos); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment