Svelte and urql: operationStore isn't reactive?

Viewed 197

When a prop passed from the parent changes, and is used as a parameter of an urql query, the query does not seem to be reexecuted.

I see many examples such as:

export let id;
const store = operationStore(query, { id })
query(store)

But why there doesn't seem to be any example available, where we want to reexecute the query simply because the prop (variable id in example above) changed?

I must be missing something big or the way I design my components is wrong?

2 Answers

From the docs https://formidable.com/open-source/urql/docs/basics/svelte/

The query function accepts our store and starts using the Client to execute our query. It may only be called once for a store and lives alongside the component's lifecycle. It will automatically read changes on the operationStore and will update our query and results accordingly.

Both, updating todos.variables and $todos.variables (here todos = store) in a component for instance, will cause query to pick up the update and execute our changes.

So I think it might be possible to reactivley update the operationStore variable like this and trigger the reexecution of the query

export let id;

const store = operationStore(query, { id })

$: store.variables = {
  id
};

query(store)

Corrl's answer is fundamentally correct.

However, in practice, what I ended up usually doing was to define and use my own refreshQuery function in pages or components where props are passed as query variables, with a test to make sure the query only reruns if any of the props did actually change:

export let foo
export let bar

const store = operationStore(query, { foo, bar })

query(store)

$: refreshQuery(foo, bar)

function refreshQuery(foo, bar) {
    if ($store.variables['foo'] !== foo || $store.variables['bar'] !== bar) {
        $store.variables = { foo, bar };
    }
}
Related