Context store issue with array
Hello,
I apologize but I just allowed myself to make a second post, since now I have a codesandbox to reproduce the issue I have in my app.
Situation: I have a store in a context, and the context object also contains setters to update the store (I tried to do the same as the CounterContext in the documentation: https://www.solidjs.com/docs/latest#createcontext).
The problem is, in my app I have several components, each of them containing the value at their own index in an array of my store. And each component receives, from the context, a setter function that updates the value in the array at their index.
My problem is that when I try to update a value at an index with my setter function, it updates all the elements of the array.
I reproduced it in this codesandbox: https://codesandbox.io/p/sandbox/jovial-fast-s7z0xs?file=%2Fsrc%2FApp.tsx&selection=%5B%7B%22endColumn%22%3A5%2C%22endLineNumber%22%3A12%2C%22startColumn%22%3A5%2C%22startLineNumber%22%3A12%7D%5D
=> I just made two buttons, each of them containing the value at the index 0 and 1 of the array in the store context. On click on the button, the setter function from the context is called, and is supposed to increment the value at the right index. We can see that the values in both buttons are incremented.
=> The code is a bit complicated for only two buttons, but in my app I need a lot of fetched data, initialize stuff etc, I tried to reproduce the architecture.
I don't know what I'm doing wrong here. Thank you for reading (again maybe), I wish you a nice day!
jovial-fast-s7z0xs
CodeSandbox is an online editor tailored for web applications.
SolidJS
Solid is a purely reactive library. It was designed from the ground up with a reactive core. It's influenced by reactive principles developed by previous libraries.
1 Reply
Ok, I fixed the issue, if someday someone has the same problem:
I replaced the initialization:
setMyContext("myArray", [
{
...mockMyObject,
},
{
...mockMyObject,
},
]);
with:
setMyContext("myArray", [
JSON.parse(JSON.stringify(mockMyObject)),
JSON.parse(JSON.stringify(mockMyObject)),
]);
I guess there are better ways to clone, but that fixed the issue.