S
SolidJS8mo ago
CatNoir

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.
No description
5 Replies
TaQuanMinhLong
TaQuanMinhLong8mo ago
It seems like you've rendered the whole <input> for each input value
bigmistqke
bigmistqke8mo ago
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.
CatNoir
CatNoirOP8mo ago
Thanks! I like the Index way
bigmistqke
bigmistqke8mo ago
having looked a bit deeper at the code: it's a bit unorthodox to do
setOptions((opts) => {
opts[i] = value;
return opts;
});
setOptions((opts) => {
opts[i] = value;
return opts;
});
You are updating the options-signal, but it will not actually cause the effects that depend on options to react, since you are mutating the array directly. It's practically the same as doing options()[i] = value, which is a bit hacky. If you would have a 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.
CatNoir
CatNoirOP8mo ago
interesting, i will change it to createStore, thanks!
Want results from more Discord servers?
Add your server