Created
July 22, 2019 20:46
-
-
Save BetterProgramming/b6b06c11f1040ffc4964b33188525889 to your computer and use it in GitHub Desktop.
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 useFetch = endpoint => { | |
const defaultHeader = { | |
Accept: "application/json", | |
"Content-Type": "application/json" | |
}; | |
const customFetch = ( | |
url, | |
method = "GET", | |
body = false, | |
headers = defaultHeader | |
) => { | |
const options = { | |
method, | |
headers | |
}; | |
if (body) options.body = JSON.stringify(body); | |
return fetch(url, options) | |
.then(response => response.json()) | |
.catch(err => { | |
throw new Error(err); | |
}); | |
}; | |
const get = id => { | |
const url = `${endpoint}${id ? `/${id}` : ""}`; | |
return customFetch(url); | |
}; | |
const post = (body = false) => { | |
if (!body) throw new Error("to make a post you must provide a body"); | |
return customFetch(endpoint, "POST", body); | |
}; | |
const put = (id = false, body = false) => { | |
if (!id || !body) | |
throw new Error("to make a put you must provide the id and the body"); | |
const url = `${endpoint}/${id}`; | |
return customFetch(url, "PUT", body); | |
}; | |
const del = (id = false) => { | |
if (!id) | |
throw new Error("to make a delete you must provide the id and the body"); | |
const url = `${endpoint}/${id}`; | |
return customFetch(url, "DELETE"); | |
}; | |
return { | |
get, | |
post, | |
put, | |
del | |
}; | |
}; | |
export default useFetch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment