Question: How to use changeDetection with dynamic datas into child component
Hi! I was so exited to try the new Stencil compiler. Awsome!! Too fast!!!
Currently playing with Stencil and have a bug with the changeDetection into child component :-( The data is not updated when the change coming from the parent element. Shemas:
- parent use child component with datas from array ->
- childComponent send event emitter to parent on click ->
- parent create new array of data from original datas array ->
- parent update item into array by id ->
- parent update original array by the new one -> Result: bug: child do not change cause original array is updated BEFORE parent assigne new state...
handleClick(todoChanged:Todo):void {
// create new const with each element of this.todos Array (use ES6 is same as .concat())
const updatedTodos = [...this.todos]
// update todo by id
updatedTodos.map((todo:Todo) => {
(todo._id === todoChanged._id) ? todo.complete = !todo.complete : null
return todo
})
// update this.todos to re-render and update view...
console.log('Bug: todos list is updated before reassign-> ', this.todos)
this.todos = updatedTodos // here is the re-assignation ?? waf ??
}
I've a sample code in situation just here: sample code
Any ideas, help is welcom ;-)
I have the same problem - also with todo example and toggle of completed. The change detection doesn't seem to work for a boolean in an object.
My workaround is to recreate the whole todo item and replace it in the array. See my code
Here is my super-rough, initial understanding: it doesn't do change detection of stuff inside objects or arrays; it does change detection of primitive values of property and state fields only. If you change something inside an object or array, you are supposed to pass a new object or array. See:
https://stenciljs.com/docs/decorators
section "Change Detection".
(I'm super-familiar with deep change detection in Angular and other tools... offhand I get the feeling that going that direction in Stencil might break the notion of a compiling down to very lightweight web components. But I just arrived... and could be 100% wrong.)
Maybe add another decorator like @DynamicState() that is the same as @State() but does deep change detection. If this feature would bloat Stencil then I'd prefer it be left out, but I think this point needs to be communicated more clearly to users, otherwise this topic is going to frustrate almost 100% of new users. Having to concat([]) an array to force an update is awkward.
Change detection can be a much larger undertaking than it sounds. Angular does this, and does a great job of it - but also has been developing and optimizing it for a long time, and the impact and API surface inevitably spreads broadly across the framework.
(For example: when to do change detection, is not an easy question. Angular's answer is to use Zone.js to know exactly when things might have changes. Zone.js needs to lace in to numerous browser APIs - something that consumers of a "very light weight" web component may not be eager to accept as a condition of using such a component.)
Currently our change detection is really based on original value changes. So if you want to change an array or an object you will need to set it to a new array or object. This might seem cumbersome but it is the simplest way to resolve changes. I would update the code and use spread operators which are fully supported in Typescript.
In your example the actual problem is that array map does not change the original array it returns a new copy of the array so just add that as an assignment. It would be simpler to do this.
handleClick(todoChanged:Todo):void {
// update todo by id
this.todos = this.todos.map((todo: Todo) => {
(todo._id === todoChanged._id) ? todo.complete = !todo.complete : null
return todo;
});
}
this will not woking. Is my 1st test and thing not working cause .map() not realy return à new arry without change current array maped. Don't know why...
But 've find a cusome way to do it without changing current maped array... i don't use .map() but .filter() to extract unchanged item, then i put unchanged items + changed item into a new array. Here the working code:
handleClick(todoChanged:ITodo):void {
// update todo ...
todoChanged.complete = !todoChanged.complete;
// assign new todo[] to this.todos
this.todos = [
// extract all unchanged todos
...this.todos.filter(t=>t._id !== todoChanged._id),
// add changed todo
todoChanged
]
}
Enjoy ;-)
@FazioNico Handling the data in an immutable matter is indeed somewhat inconvenient. For the solution you show, you have mutated the individual todo item in place - it probably works in the scenario but would break and others. Handling both the item and the list in an immutable way can also be done about as succinctly:
https://github.com/kylecordes/stencil-todomvc/blob/master/src/components/todo-mvc/todo-mvc.tsx#L65
I know this is dead but I just want to add for future searchers, Fazio's problem had nothing to do with how he used map because he first cloned the array anyway. He should have used it like jthoms1 suggests because it would be more readable. But his actual problem is that he's mutating values inside the array (a bug that still exists in jthoms1's code) and the complaint is that whatever component that depends on the todo isn't seeing the change. The solution is he needs to copy the inner objects (with spread) as suggested.
handleClick(todoChanged:Todo):void {
// update todo by id
this.todos = this.todos.map((todo: Todo) => {
// return the original todo most of the time, but when toggling todo.complete, return a copy.
return (todo._id === todoChanged._id) ? {...todo, complete: !todo.complete} : todo
});
}
In other words, makes a new copy of todos, and if the inner todo is the todoChanged id, copy it too. That will re-render any component that depended on the todo.
This could be made to look less horrible, like you could probably use todo === todoChanged but I'd have to know the code.