Why does adding a new field duplicate the value?
https://stackblitz.com/edit/github-zon5da?file=src%2FApp.tsx
When entering a value in the input field, and clicking on the "Add" button, it seems to be duplicating the input value. Why is this happening and how do i prevent this?
Thanks.
5 Replies
It seems like you've rendered the whole <input> for each input value
I don't know exactly what is causing this bug, but I know how you could solve it:
1. make the option-type something like
{ message: string }
. For works with referential equality, and something while comparing strings/primitives goes wrong.
2. or use Index
instead of For
, since there it's only the order that matters.Thanks! I like the
Index
wayhaving looked a bit deeper at the code: it's a bit unorthodox to do
You are updating the options-signal, but it will not actually cause the effects that depend on a bit hacky.
If you would have a
options
to react, since you are mutating the array directly. It's practically the same as doing options()[i] = value
, which is createEffect(() => console.log(props.option))
in your OptionItem-component you will see that it will only log when you add a new option, because then you are doing the spread [...options(), '']
.
On the other hand, if you do spread on each setOption
you will see (with For
) that it will actually re-render/re-run the whole component with each update, because the reference of the value changed.
To test: add console.log('mount')
to the component-body and you will see it logs on each update. This is something you want to prevent in solid, because it means you are re-creating dom-elements everytime.
Index
will help here, since it makes a signal for each value of its input-array.
I would also advice to use createStore
instead of a raw signal for objects/arrays. Then u can just update properties without having to think too much about referential equality and spreading stuff.interesting, i will change it to createStore, thanks!