SvelteStack / svelte-query

Performant and powerful remote data synchronization for Svelte
https://sveltequery.vercel.app
MIT License
814 stars 31 forks source link

feat(queries): add setEnabled function to queries and infinite queries #33

Closed SomaticIT closed 3 years ago

SomaticIT commented 3 years ago

In some situations, we need to enable or disable queries using svelte reactive statements.

We can do this using the setOptions method but it forces us to pass all options. It could be very useful to have a setEnabled shortcut function which reuse existing options and only update the enabled option.

It allows this code:

<script>
  import { useQuery } from '@sveltestack/svelte-query'

  let isQueryEnabled = false;

  const queryResult = useQuery('projects', getProjects, { enabled: isQueryEnabled })
  $: queryResult.setOptions('projects', getProjects, { enabled: isQueryEnabled })
</script>

to become

<script>
  import { useQuery } from '@sveltestack/svelte-query'

  let isQueryEnabled = false;

  const queryResult = useQuery('projects', getProjects)
  $: queryResult.setEnabled(isQueryEnabled)
</script>

It makes the code more readable and understandable.

Do you agree?

amen-souissi commented 3 years ago

Thanks :) Hummm, the others options will be jealous :grin: . Can we generate dynamically a function for each option ? and next we can expose these functions from an "updater" object. what do you think ?

SomaticIT commented 3 years ago

Hmmm... I'm not sure that all options need this reactivity.

Maybe a good way to handle all other cases would be to add a function named updateOptions or mergeOptions that will merge given options with existing ones.

eg:

function mergeOptions(options: UseQueryOptions<TQueryFnData, TError, TData>): void {
    observer.setOptions({ ...observer.options, ...options })
}

What do you think?

amen-souissi commented 3 years ago

Yes, cool... it seems ok for me 👍

SomaticIT commented 3 years ago

Do you have a preference on naming?

amen-souissi commented 3 years ago

maybe updateOptions :)

SomaticIT commented 3 years ago

Hi @amen-souissi,

I added the updateOptions features about 10 days ago. Did you have time to review?

Is there something missing before merging?

amen-souissi commented 3 years ago

I'm so sorry I haven't seen the changes :( ... merged and released 👍

SomaticIT commented 3 years ago

There is absolutely no problem 😁 !

Thank you for merging and releasing this, I will update my stack.

saturnonearth commented 3 years ago

Can this apply to, useQueries, as well?