posva / pinia-colada

🍹 The smart data fetching layer for Pinia
https://pinia-colada.esm.dev/
MIT License
761 stars 10 forks source link

A way to avoid using outside state #11

Open posva opened 6 months ago

posva commented 6 months ago

maybe a defineQuery(() => {}) to allow using globals and creating global state associated with the query (e.g. a page?).

Currently one can try to do this:

<script setup lang="ts">
const page = ref(1)
useQuery({
  query() {
     return fetchData(page.value)
  },
  key: () => ['key', page.value]
})
<script>

But this can fail in some scenarios, notably if the same key is used in a different component or if this gets abstracted with

export const useSomeData = () => {
const page = ref(1)
return useQuery({
  query() {
     return fetchData(page.value)
  },
  key: () => ['key', page.value]
})
}

and used in multiple components, the page will end up scoped to the first component that calls it. Both components will create a page ref but only the first one will be used within query and key. Therefore, if the first component is unmounted while the other still lives, the page ref will not be reactive anymore, breaking the usage.

Notes

posva commented 6 months ago

There should also be an equivalent for defineMutation()

posva commented 6 months ago

I think a good version would be defineQuery(() => { ...}) similar to a setup store. This looks like a composable and behaves like one except it's a singleton

posva commented 3 months ago

This is partially done with https://pinia-colada.esm.dev/guide/queries.html#Reusable-Queries but it only mentions reusable queries while defineQuery() covers more than that as it can encapsulate more than than.