0

Here is my fetcher and my application is becoming too bulky that i wouldn't want to be calling it in evvery component, how do i configure the fetcher to be accessible everywhere in my application.

     const fetcher = (url) => axios.get(url).then((resp) => resp);

I also want to set a default baseURL for axios in my application so i wouldn't have to be using the full url everytime i'm trynna make a request, so i did

    axios.defaults.baseURL= "https://dog.ceo/api/breeds/image/random"

in my App.js, but it doesn't work.

Is there a better way to achieve these two problems using SWR?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Leyksnal
  • 13
  • 5

2 Answers2

0

It's possible by creating new axios instance with whole config and then import it anywhere you want to make a call instead of importing axios package.

e.g.

in api.js

import { axios } from 'axios';

export const axiosInstance = axios.create({
  baseURL: 'https://api.example.com'
});

in any other file when you want to use it

import { axiosInstance } from 'path/api'

axiosInstance.get('/pathAfterBaseUrl')
Szymon Pancerz
  • 237
  • 1
  • 3
  • I did create new Axios instance and and my fetcher as well in a config file then I was able to import it and use it anywhere within my application, thanks that was really helpful. – Leyksnal Jul 31 '22 at 22:02
0

Here is my solution.

In Api.js

const instance = axios.create({
  baseURL: 'https://your-api.com/v1',
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
    authorization: "Bearer " + token,
  },
});
export default instance;

Then use it in swr's fetcher function

import instance from './Api.js';

const fetcher = async (key, params) => {
  const resp = await instance.get(`/route?id=${key}&param=${params}`).then(res => res.data);
  return resp;
};
const { data, error } = useSWR([key, params], fetcher);
  
Paing Khant
  • 1
  • 1
  • 1