Skip to content

Instantly share code, notes, and snippets.

@Somtuzy
Created July 4, 2023 19:50
Show Gist options
  • Save Somtuzy/71e191810919bd848df7f9cd8a1cac19 to your computer and use it in GitHub Desktop.
Save Somtuzy/71e191810919bd848df7f9cd8a1cac19 to your computer and use it in GitHub Desktop.
// This stores the token in your local storage
const setAuthToken = (token) => {
localStorage.setItem('token', token)
}
// This extracts the token from your local storage
const getAuthToken = () => {
return localStorage.getItem('token')
}
const fetchAuthToken = async (method, url, requestBody = '') => {
try {
let token = ''
if(method === 'post') {
const response = await axios.post(url, requestBody)
token = response.data.data.token
}
if(method === 'get') {
const response = await axios.get(url)
token = response.data.data.token
}
setAuthToken(token)
} catch(err) {
console.log(err)
}
}
// Examples:
// Call this in your google auth component
fetchAuthToken('get', 'https://balethriftstore.onrender.com/api/v1/auth/google')
// Call this in your signup component
fetchAuthToken('post', 'https://balethriftstore.onrender.com/api/v1/auth/signup', {fullname: 'john doe', email: 'johndoe@gmail.com', password: 1234})
// Call this in your login component
fetchAuthToken('post', 'https://balethriftstore.onrender.com/api/v1/auth/login', {email: 'johndoe@gmail.com', password: 1234})
// Call this when you want to get from or post to a protected route.
const makeARequestWithAuthToken = async (method, url, requestBody = '') => {
try {
let response = ''
if(method === 'post') {
response = await axios.post(url, requestBody, {
headers: {
Authorization: `Bearer ${getAuthToken()}`
}
})
}
if(method === 'get') {
response = await axios.get(url, {
headers: {
Authorization: `Bearer ${getAuthToken()}`
}
})
}
if(method === 'delete') {
response = await axios.delete(url, {
headers: {
Authorization: `Bearer ${getAuthToken()}`
}
})
}
if(method === 'put') {
response = await axios.put(url, requestBody, {
headers: {
Authorization: `Bearer ${getAuthToken()}`
}
})
}
if(method === 'patch') {
response = await axios.patch(url, requestBody, {
headers: {
Authorization: `Bearer ${getAuthToken()}`
}
})
}
return response.data
} catch(err) {
console.log(err);
}
}
// Examples:
// Call this to fetch users
makeARequestWithAuthToken('get', 'https://balethriftstore.onrender.com/api/v1/users')
// Call this to create products
makeARequestWithAuthToken('post', 'https://balethriftstore.onrender.com/api/v1/products', {title: 'milk', price: 500})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment