SolidJSS
SolidJS7mo ago
37 replies
gsoutz

How to sync two different signals inside a store maybe

I have an array and an index to the array defined separately as two signals, here I've demonstrated:
import { batch, createComputed, createMemo, createSignal, on, untrack } from "solid-js";
import { createStore } from "solid-js/store";
import { render } from "solid-js/web";


function App() {

  const [my_array, set_my_array] = createSignal([3])

  const array = createMemo(() => my_array())

  const [p_store, set_p_store] = createStore({
    get array() {
      return array()
    },
    cursor: 0
  })


  const fail_computation = createMemo(() => p_store.array[p_store.cursor].array_access)

  batch(() => {
    set_my_array([1, 2, 3, 4])
    set_p_store('cursor', 3)
  })

  const on_reset_array = () => {
    set_my_array([])
  }
  

  return (<><button onClick={on_reset_array}></button> </>)
}


render(() => <App />, document.getElementById("app")!);

.

Now when I update the array for example reset it, the cursor still shows the old location which causes an out of bounds error. How do I structure my code to prevent this kind of issue, and still be able to have a computation to access inside the array reactively.

https://playground.solidjs.com/anonymous/f3de692a-5ace-4a08-a51c-dc8541ec0b85
Quickly discover what the solid compiler will generate from your JSX template
Was this page helpful?