Skip to content

Instantly share code, notes, and snippets.

@iftkharhussain
Created August 23, 2021 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iftkharhussain/5892bb3c75ad144b8340fa2ff229dfd6 to your computer and use it in GitHub Desktop.
Save iftkharhussain/5892bb3c75ad144b8340fa2ff229dfd6 to your computer and use it in GitHub Desktop.
It is common function to fetch or post data using fetch.
export const checkAuth = () => {
let localAuth = localStorage.getItem('auth')
if(localAuth){
return JSON.parse(localAuth)
}
return false
}
export const requestHelper = (url, method, headers, data) => {
let token = checkAuth()
let requestLoad = {
method,
headers: {
...headers,
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
};
if(token){
requestLoad = {
method,
headers: {
...headers,
Accept: "application/json",
"Content-Type": "application/json",
"Authorization": `Bearer ${token.jwt ? token.jwt: '..'}`
},
body: JSON.stringify(data)
};
}
let getLoad = {
method,
headers: { ...headers, "Content-Type": "application/json" }
};
if(token){
getLoad = {
method,
headers: { ...headers, "Content-Type": "application/json", "Authorization": `Bearer ${token.jwt ? token.jwt: '..'}` }
};
}
return fetch(`${url}`, method === "GET" ? getLoad : requestLoad);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment