Skip to content

Instantly share code, notes, and snippets.

@deadkff01
Created July 19, 2020 00:53
Show Gist options
  • Save deadkff01/275e31be92e6495c15d5a4d8500adb05 to your computer and use it in GitHub Desktop.
Save deadkff01/275e31be92e6495c15d5a4d8500adb05 to your computer and use it in GitHub Desktop.
useSwr config with axios and fetch
const api = axios.create({
baseURL: "http://localhost:8080/",
});
api.interceptors.response.use(
(response) => response.data,
(error) => Promise.reject(error)
);
export const useRequest = (config) => {
const { path, body, method, headerParam } = config;
if (!path) {
throw new Error("Path is required");
}
const requestConfig = (response) => ({
url: response,
method,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
...headerParam,
},
...(body ? { body: JSON.stringify(body) } : null),
});
const url = baseUrl + path;
const { data, error, mutate } = useSwr(url, (response) =>
api(requestConfig(response))
);
return { data, error, mutate };
};
// USING FETCH NATIVE API
export const useRequest = (config) => {
const { path, body, method, headerParam } = config;
if (!path) {
throw new Error("Path is required");
}
const fetcher = (url) =>
fetch(url, {
method,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
...headerParam,
},
...(body ? { body: JSON.stringify(config.body) } : null),
}).then((response) => response.json());
const url = baseUrl + path;
const { data, error } = useSwr(url, fetcher);
return { data, error };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment