# Axios API Calls

### Axios API call using SWR

Product values have been initialized using useSWR with Axios fetcher, like below:

{% tabs %}
{% tab title="NEXT (TS)" %}
{% code title="src/api/products.ts" %}

```typescript
export function useGetRelatedProducts(id: string) {
  const URL = [endpoints.related, { id, endpoints: 'products' }];

  const { data, isLoading, error, isValidating } = useSWR(URL, fetcherPost, {
    revalidateIfStale: false,
    revalidateOnFocus: false,
    revalidateOnReconnect: false
  });

  const memoizedValue = useMemo(
    () => ({
      relatedProducts: data as Products[],
      relatedProductsLoading: isLoading,
      relatedProductsError: error,
      relatedProductsValidating: isValidating,
      relatedProductsEmpty: !isLoading && !data?.length
    }),
    [data, error, isLoading, isValidating]
  );

  return memoizedValue;
}
```

{% endcode %}
{% endtab %}

{% tab title="NEXT (JS)" %}
{% code title="src/api/products.js" %}

```javascript
export function useGetRelatedProducts(id) {
  const URL = [endpoints.related, { id, endpoints: 'products' }];

  const { data, isLoading, error, isValidating } = useSWR(URL, fetcherPost, {
    revalidateIfStale: false,
    revalidateOnFocus: false,
    revalidateOnReconnect: false
  });

  const memoizedValue = useMemo(
    () => ({
      relatedProducts: data,
      relatedProductsLoading: isLoading,
      relatedProductsError: error,
      relatedProductsValidating: isValidating,
      relatedProductsEmpty: !isLoading && !data?.length
    }),
    [data, error, isLoading, isValidating]
  );

  return memoizedValue;
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

You can mutate the product list with an Axios call, like below,

{% tabs %}
{% tab title="NEXT (TS)" %}
{% code title="src/api/products.ts" %}

```typescript
export async function productFilter(filter: ProductsFilter) {
  const newProducts = await axios.post(endpoints.key + endpoints.filter, { filter });

  // to update local state based on key
  mutate(
    endpoints.key + endpoints.list,
    (currentProducts: any) => {
      return {
        ...currentProducts,
        products: newProducts.data
      };
    },
    false
  );
}
```

{% endcode %}
{% endtab %}

{% tab title="NEXT (JS)" %}
{% code title="src/api/products.js" %}

```javascript
export async function productFilter(filter) {
  const newProducts = await axios.post(endpoints.key + endpoints.filter, { filter });

  // to update local state based on key
  mutate(
    endpoints.key + endpoints.list,
    (currentProducts) => {
      return {
        ...currentProducts,
        products: newProducts.data
      };
    },
    false
  );
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

### Set the default axios baseURL for calling the API

Open `next.config.js` file and edit NEXT\_APP\_API\_URL.

{% code title="next.config.js" %}

```javascript
env: {
    NEXT_APP_API_URL:
    ..
}
```

{% endcode %}

Axios has been configured in the folder **`src\utils\axios`**

### Example 1: With baseUrl

{% tabs %}
{% tab title="NEXT (TS)" %}
{% code title="src/utils/axios.ts" %}

```typescript
import axios, { AxiosRequestConfig } from 'axios';
import { getSession } from 'next-auth/react';

const axiosServices = axios.create({ baseURL: process.env.NEXT_APP_API_URL });


// ==============================|| AXIOS - FOR MOCK SERVICES ||============================== //

axiosServices.interceptors.request.use(
  async (config) => {
    const session = await getSession();
    if (session?.token.accessToken) {
      config.headers['Authorization'] = `Bearer ${session?.token.accessToken}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
```

{% endcode %}
{% endtab %}

{% tab title="NEXT (JS)" %}
{% code title="src/utils/axios.js" %}

```javascript
import axios from 'axios';
import { getSession } from 'next-auth/react';

const axiosServices = axios.create({ baseURL: import.meta.env.VITE_APP_API_URL || 'http://localhost:3010/' });

// ==============================|| AXIOS - FOR MOCK SERVICES ||============================== //

axiosServices.interceptors.request.use(
  async (config) => {
    const session = await getSession();
    if (session?.token.accessToken) {
      config.headers['Authorization'] = `Bearer ${session?.token.accessToken}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
```

{% endcode %}
{% endtab %}
{% endtabs %}

### Example 2: Without baseUrl

You can set the entire URL in the Axios request. Do not use common Axios instances  **`src\utils\axios`** instead, use the Axios library.

{% tabs %}
{% tab title="NEXT (TS)" %}
{% code title="src\utils\axios.ts" %}

```typescript
import { useCallback, useState } from 'react';

// third-party
import axios from 'axios';

// ==============================|| AXIOS - USER ||============================== //

function UserList() {
  const [users, setUsers] = useState([]);

  const getUsers = useCallback(async () => {
    try {
      const response = await axios.get('https://www.domain-xyz.com/api/users');
      setUsers(response.data.users);
    } catch (error) {
      console.log(error);
    }
  }, []);

  useEffect(() => {
    getUsers();
  }, [getUsers]);

  return (
    <div>
      {users.map((user: UserProfile[], index: number) => (
        <div key={index}>{user.name}</div>
      ))}
    </div>
  );
}
```

{% endcode %}
{% endtab %}

{% tab title="NEXT (JS)" %}
{% code title="src\utils\axios.js" %}

```javascript
import { useCallback, useState } from 'react';

// third-party
import axios from 'axios';

// ==============================|| AXIOS - USER ||============================== //

function UserList() {
  const [users, setUsers] = useState([]);

  const getUsers = useCallback(async () => {
    try {
      const response = await axios.get('https://www.domain-xyz.com/api/users');
      setUsers(response.data.users);
    } catch (error) {
      console.log(error);
    }
  }, []);

  useEffect(() => {
    getUsers();
  }, [getUsers]);

  return (
    <div>
      {users.map((user, index) => (
        <div key={index}>{user.name}</div>
      ))}
    </div>
  );
}
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://phoenixcoded.gitbook.io/able-pro/nextjs/axios-api-calls.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
