Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

feat(nuxt): make useFetch options reactive #8374

Merged
merged 1 commit into from
Oct 21, 2022
Merged

feat(nuxt): make useFetch options reactive #8374

merged 1 commit into from
Oct 21, 2022

Conversation

danielroe
Copy link
Member

πŸ”— Linked issue

resolves nuxt/nuxt#14342

❓ Type of change

  • πŸ“– Documentation (updates to the documentation or readme)
  • 🐞 Bug fix (a non-breaking change that fixes an issue)
  • πŸ‘Œ Enhancement (improving an existing functionality like performance)
  • ✨ New feature (a non-breaking change that adds functionality)
  • ⚠️ Breaking change (fix or feature that would cause existing functionality to change)

πŸ“š Description

This allows passing refs/computed properties as fetch options (e.g. for a param value), and automatically refetching when these values change.

πŸ“ Checklist

  • I have linked an issue or discussion.
  • I have updated the documentation accordingly.

@danielroe danielroe added enhancement New feature or request 🍰 p2-nice-to-have Priority 2: nothing is broken but it's worth addressing labels Oct 20, 2022
@danielroe danielroe requested a review from pi0 October 20, 2022 23:53
@danielroe danielroe self-assigned this Oct 20, 2022
@codesandbox
Copy link

codesandbox bot commented Oct 20, 2022

CodeSandbox logoCodeSandbox logoΒ  Open in CodeSandbox Web Editor | VS Code | VS Code Insiders

@netlify
Copy link

netlify bot commented Oct 20, 2022

βœ… Deploy Preview for nuxt3-docs ready!

Name Link
πŸ”¨ Latest commit a58e0ee
πŸ” Latest deploy log https://app.netlify.com/sites/nuxt3-docs/deploys/6351df7e576b4e0008fc5255
😎 Deploy Preview https://deploy-preview-8374--nuxt3-docs.netlify.app
πŸ“± Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site settings.

@pi0 pi0 merged commit 69a6a86 into main Oct 21, 2022
@pi0 pi0 deleted the feat/reactive-fetch branch October 21, 2022 08:13
@JorenSynaeveTM
Copy link

Hi Daniel. I don't know where to respond, so I'm posting my question here. I'm having issues getting this to work. I have the following code in my page:

...
const page = computed(() => {
  return parseInt(useRoute().query.page) || 1;
});

/* This part worked with the pagination as expected
const { pending, data } = useAsyncData(
  "test",
  () =>
    $fetch(
      `${useRuntimeConfig().public.API_BASE_URL}/api/productlist?page=${
        page.value
      }&includeUser=true`,
      {
        headers: {
          Authorization: `Bearer ${useCookie("apiToken").value}`,
        },
      }
    ),
  {
    watch: [page],
  }
);
*/

/* This part does not work */
const { pending, data } = myAsyncData(
  "test",
  `/api/productlist?page=${page.value}&includeUser=true`,
  {},
  {
    watch: [page],
  }
);

...

When trying to extract this logic to a custom composable for better error handling and adding a bearer token, it stopped working. Here is my custom composable:

import { AsyncDataOptions, UseFetchOptions } from "nuxt/dist/app/composables";

export const myAsyncData = (key: string, url: string, fetchOptions?: UseFetchOptions<unknown>, asyncDataOptions?: AsyncDataOptions<unknown>) => {
    const config = useRuntimeConfig();

    return useAsyncData(key, () =>
        $fetch(
            config.public.API_BASE_URL + url,
            {
                ...fetchOptions,
                async onRequest({ request, options }) {
                    const token = useCookie("apiToken");

                    if (token.value) {
                        options.headers = {
                            ...options.headers,
                            Authorization: `Bearer ${token.value}`,
                        };
                    }

                    console.log("[fetch request]");
                }
            }
        ),
        {
            ...asyncDataOptions
        });
};

Could you please take a look on why this is not working?
Ps: If I have to move this comment somewhere else, please tell me to do so.

Copy link
Member Author

yes, this is probably not the right place. if you have a follow-up question, would you open a discussion instead?

you should instead do something like this:

const { pending, data } = await useAsyncData(
  'test',
  '/api/productlist',
  {
    params: {
      page,
      includeUser: true
    }
  }
)

... and that should work, automatically watching page. You can pass params though and it should also work with myAsyncData.

@pi0 pi0 mentioned this pull request Nov 3, 2022
@yashika
Copy link

yashika commented Nov 6, 2022

awesome!

@AaronConlon
Copy link

Waited a long time.

@AaronConlon
Copy link

Thanks bro

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
3.x enhancement New feature or request 🍰 p2-nice-to-have Priority 2: nothing is broken but it's worth addressing
Projects
None yet
Development

Successfully merging this pull request may close these issues.

useFetch does not account for params change
5 participants