specify the base url when using usefetch in nuxt in typescript

To specify the base URL when using useFetch in Nuxt with TypeScript, you can create a separate fetch utility function that sets the base URL and returns a new useFetch hook with pre-configured options.

Here is an example implementation for this approach:

index.ts
// utils/fetch.ts
import useFetch from 'fetch-hooks';
import { useState } from '@nuxtjs/composition-api';

// Define a custom fetch function with the base URL set
export const fetchAPI = (url: string) => {
  return fetch(`https://api.example.com${url}`);
}

// Define the useFetch hook with options pre-configured
export const useAPIFetch = () => {
  const [isLoading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const apiFetch = useFetch(fetchAPI, {
    onLoading: () => setLoading(true),
    onError: (err) => setError(err),
    onData: () => setLoading(false),
  });

  return { ...apiFetch, isLoading, error };
};
652 chars
23 lines

In this example, we have defined a separate fetchAPI utility function that sets the base URL to https://api.example.com. We then use this function to create a pre-configured useFetch hook with the useAPIFetch function.

To use this hook in your component, import useAPIFetch from your custom fetch.ts file:

index.ts
<script lang="ts">
import { defineComponent } from '@nuxtjs/composition-api';
import { useAPIFetch } from '../utils/fetch';

export default defineComponent({
  setup() {
    const { data, error, isLoading } = useAPIFetch();

    return {
      data,
      error,
      isLoading,
    }
  }
});
</script>
304 chars
17 lines

In this example, we use useAPIFetch instead of the standard useFetch hook, and the base URL is automatically set to https://api.example.com whenever a request is made.

gistlibby LogSnag