From 9c478ee16eea288960a4a9a07caca941507c1309 Mon Sep 17 00:00:00 2001 From: Mahdi Boomeri <65359713+mahdiboomeri@users.noreply.github.com> Date: Mon, 5 Dec 2022 16:37:33 +0330 Subject: [PATCH] feat: `useNuxtData` composable (#9262) Co-authored-by: Daniel Roe Co-authored-by: Pooya Parsa --- .../3.api/1.composables/use-nuxt-data.md | 73 +++++++++++++++++++ .../nuxt/src/app/composables/asyncData.ts | 15 +++- packages/nuxt/src/app/composables/index.ts | 2 +- packages/nuxt/src/imports/presets.ts | 1 + 4 files changed, 89 insertions(+), 2 deletions(-) create mode 100644 docs/content/1.docs/3.api/1.composables/use-nuxt-data.md diff --git a/docs/content/1.docs/3.api/1.composables/use-nuxt-data.md b/docs/content/1.docs/3.api/1.composables/use-nuxt-data.md new file mode 100644 index 0000000000..898042695e --- /dev/null +++ b/docs/content/1.docs/3.api/1.composables/use-nuxt-data.md @@ -0,0 +1,73 @@ +# `useNuxtData` + +`useNuxtData` gives you access to the current cached value of `useAsyncData`, `useLazyAsyncData`, `useFetch` and `useLazyFetch` with explicitly provided key. + +::Alert +This feature is not released yet. You can beta test using [Edge Channel](https://nuxt.com/docs/guide/going-further/edge-channel). +:: + +## Type + +```ts +useNuxtData (key: string): { data: Ref } +``` + +## Examples + +### Show stale data while fetching in the background + +The example below shows how you can use cached data as a placeholder while the most recent data is being fetched from the server. + +```ts [archive.vue] +// We can access same data later using 'posts' key +const { data } = await useFetch('/api/posts', { key: 'posts' }) +``` + +```ts [single.vue] +// Access to the cached value of useFetch in archive.vue +const { data: posts } = useNuxtData('posts') + +const { data } = await useFetch(`/api/posts/${postId}`, { + key: `post-${postId}`, + default: () => { + // Find the individual post from the cache and set it as the default value. + return posts.value.find(post => post.id === postId) + } +}) +``` + +### Optimistic Updates + +We can leverage the cache to update the UI after a mutation, while the data is being invalidated in the background. + +```ts [todos.vue] +// We can access same data later using 'todos' key +const { data } = await useFetch('/api/todos', { key: 'todos' }) +``` + +```ts [add-todo.vue] +const newTodo = ref('') +const previousTodos = ref([]) + +// Access to the cached value of useFetch in todos.vue +const { data: todos } = useNuxtData('todos') + +const { data } = await useFetch('/api/addTodo', { + key: 'addTodo', + method: 'post', + body: { + todo: newTodo.value + }, + onRequest () { + previousTodos.value = todos.value // Store the previously cached value to restore if fetch fails. + + todos.value.push(newTodo.value) // Optimistically update the todos. + }, + onRequestError () { + todos.value = previousTodos.value // Rollback the data if the request failed. + }, + async onResponse () { + await refreshNuxtData('todos') // Invalidate todos in the background if the request succeeded. + } +}) +``` diff --git a/packages/nuxt/src/app/composables/asyncData.ts b/packages/nuxt/src/app/composables/asyncData.ts index eba8f205a5..8543877409 100644 --- a/packages/nuxt/src/app/composables/asyncData.ts +++ b/packages/nuxt/src/app/composables/asyncData.ts @@ -1,4 +1,4 @@ -import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from 'vue' +import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref, toRef } from 'vue' import type { Ref, WatchSource } from 'vue' import { NuxtApp, useNuxtApp } from '../nuxt' import { createError } from './error' @@ -268,6 +268,19 @@ export function useLazyAsyncData< return useAsyncData(key, handler, { ...options, lazy: true }, null) } +export function useNuxtData (key: string): { data: Ref } { + const nuxt = useNuxtApp() + + // Initialize value when key is not already set + if (!(key in nuxt.payload.data)) { + nuxt.payload.data[key] = null + } + + return { + data: toRef(nuxt.payload.data, key) + } +} + export async function refreshNuxtData (keys?: string | string[]): Promise { if (process.server) { return Promise.resolve() diff --git a/packages/nuxt/src/app/composables/index.ts b/packages/nuxt/src/app/composables/index.ts index 96b7aea648..30ddfaf90b 100644 --- a/packages/nuxt/src/app/composables/index.ts +++ b/packages/nuxt/src/app/composables/index.ts @@ -1,5 +1,5 @@ export { defineNuxtComponent } from './component' -export { useAsyncData, useLazyAsyncData, refreshNuxtData, clearNuxtData } from './asyncData' +export { useAsyncData, useLazyAsyncData, useNuxtData, refreshNuxtData, clearNuxtData } from './asyncData' export type { AsyncDataOptions, AsyncData } from './asyncData' export { useHydration } from './hydrate' export { useState } from './state' diff --git a/packages/nuxt/src/imports/presets.ts b/packages/nuxt/src/imports/presets.ts index 04e992d6ae..613a81c9c0 100644 --- a/packages/nuxt/src/imports/presets.ts +++ b/packages/nuxt/src/imports/presets.ts @@ -23,6 +23,7 @@ const appPreset = defineUnimportPreset({ imports: [ 'useAsyncData', 'useLazyAsyncData', + 'useNuxtData', 'refreshNuxtData', 'clearNuxtData', 'defineNuxtComponent',