Created
July 19, 2020 00:53
-
-
Save deadkff01/275e31be92e6495c15d5a4d8500adb05 to your computer and use it in GitHub Desktop.
useSwr config with axios and fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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