`useData` composable
Context: https://github.com/nuxt/framework/issues/7562, https://github.com/nuxt/framework/issues/7562
useState is primarily to preserve initial state between client and server. useAsyncData should be ideally used to store data but sometimes, it is more convenient to use useState and direct async logic to fill it. (usage in nuxt/content document-driven mode).
We can introduce new useData composable that acts almost same as useState but is explicitly marked as page data and can be extracted to the static payloads.
Alternatives:
-
useStateto always be extracted (like 3.0.0.rc.1) => It introduces network when it is really initial state and same between pages -
useStateto track changes => Not sure if possible at all for server but even if is, a custom async logic might initializes it before composable. It also makes implementation more complex internally -
useAsyncData=> Seems not fitting for all
This mean the data defined in useData is cleared during navigation, but in that case, at which stage?
(talking in context of full-static)
With #7567, useState will not be cleared on nav
useData is same as useAsyncData only not having an async fetcher and can be replaced for current implementation in nuxt/content of useState. Content modules shall use useData with keys specific to each page for state that is variant to each page. This way it won't be overridden but cached on CSR nav.
@pi0 great idea.
but as I saw asyncData key are not allowed jet.
Let’s say I have a compostable called „useCart“ with multiple functions „load“, „addItem“, „removeItem“ each of those functions includes an useasyncData call an return the same data (whole cart object).
It’s it better to use watch the data in each functions and sync the data to a different state (useState(„currentCart“) or is it better the use the same key for asyncData and resolve as computed(()=> nuxt._asyncData[key])?
@c-schwan If you building a global store pattern, I would advice using a combination of useState and $fetch to update them.
useAsyncData / useData are for the per-page state (while an example like useCart is a global state).
@pi0 thx, but if i use the combination of useState and $fetch then i lose the useAsyncData functionality like { server: true | false}, lazy:true.
So i have to duplicate the whole functionality fetching the data and store them