Created
August 23, 2021 16:16
-
-
Save iftkharhussain/5892bb3c75ad144b8340fa2ff229dfd6 to your computer and use it in GitHub Desktop.
It is common function to fetch or post data using fetch.
This file contains 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
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