Closed ray-delossantos closed 4 years ago
You can make a function that returns both new data and a new view, like this:
const updateData = dataNew => ({
data: dataNew,
view: (<Todos data={dataNew}/>)
});
const updateTodo = ({ data, view }) => updateData({
...data,
todo: view.target.value
});
const createTodo = ({ data, view }) => updateData({
todo: "",
todos: [...data.todos, data.todo]
});
const removeTodo = index => ({ data, view }) => updateData({
...data,
todos: data.todos.filter(
(todo, todoIndex) =>
todoIndex !== index
)
});
Example%3B%0A%0Aconst%20updateTodo%20%3D%20(%7B%20data%2C%20view%20%7D)%20%3D%3E%20updateData(%7B%0A%20%20%09...data%2C%0A%09todo%3A%20view.target.value%0A%7D)%3B%0A%0Aconst%20createTodo%20%3D%20(%7B%20data%2C%20view%20%7D)%20%3D%3E%20updateData(%7B%0A%09todo%3A%20%22%22%2C%0A%09todos%3A%20%5B...data.todos%2C%20data.todo%5D%0A%7D)%3B%0A%0Aconst%20removeTodo%20%3D%20index%20%3D%3E%20(%7B%20data%2C%20view%20%7D)%20%3D%3E%20updateData(%7B%0A%09...data%2C%0A%09todos%3A%20data.todos.filter(%0A%09%09(todo%2C%20todoIndex)%20%3D%3E%0A%09%09%09todoIndex%20!%3D%3D%20index%0A%09%09)%0A%7D)%3B%0A%0Aconst%20Todos%20%3D%20(%7B%20data%20%7D)%20%3D%3E%20(%0A%09%3Cdiv%3E%0A%09%09%3Ch1%3ETodos%3C%2Fh1%3E%0A%09%09%3Cinput%0A%09%09%09type%3D%22text%22%0A%09%09%09placeholder%3D%22What%20needs%20to%20be%20done%3F%22%0A%09%09%09value%3D%7Bdata.todo%7D%0A%09%09%09%40input%3D%7BupdateTodo%7D%0A%09%09%2F%3E%0A%09%09%3Cbutton%20%40click%3D%7BcreateTodo%7D%3ECreate%3C%2Fbutton%3E%0A%09%09%3Cfor%3D%7Btodo%2C%20index%7D%0A%09%09%09of%3D%7Bdata.todos%7D%0A%09%09%09name%3D%22ul%22%0A%09%09%3E%0A%09%09%09%3Cli%20%40click%3D%7BremoveTodo(index)%7D%3E%0A%09%09%09%09%7Btodo%7D%0A%09%09%09%3C%2Fli%3E%0A%09%09%3C%2Ffor%3E%0A%09%3C%2Fdiv%3E%0A)%3B%0A%0AMoon.use(%7B%0A%09data%3A%20Moon.data.driver(%7B%0A%09%09todo%3A%20%22%22%2C%0A%09%09todos%3A%20%5B%0A%09%09%09%22Learn%20Moon%22%2C%0A%09%09%09%22Take%20a%20nap%22%2C%0A%09%09%09%22Go%20shopping%22%0A%09%09%5D%0A%09%7D)%2C%0A%09view%3A%20Moon.view.driver(%22%23root%22)%0A%7D)%3B%0A%0AMoon.run((%7B%20data%20%7D)%20%3D%3E%20(%7B%0A%09view%3A%20(%3CTodos%20data%3D%7Bdata%7D%2F%3E)%0A%7D))%3B)
Nice, thanks for the info. I thought you had some shortcuts utility functions for this kind of repetitive code.
No problem. Utility functions for things like this usually end up being too specific. For example, this wouldn't really work if you were using more drivers (such as time
or the new http
driver). I would just encourage using the standard functional programming technique to stay DRY — creating functions!
In the examples for the main website there's the TODO App. How can one use DRY principles for removing the duplicated code?
https://kbrsh.github.io/moon/play