Skip to content

Instantly share code, notes, and snippets.

@jeffreytgilbert
Created April 20, 2024 00:25
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 jeffreytgilbert/c65f14dd107e840ee893af2ed6ebeeae to your computer and use it in GitHub Desktop.
Save jeffreytgilbert/c65f14dd107e840ee893af2ed6ebeeae to your computer and use it in GitHub Desktop.
The wrong way?
import { useAuth } from "../auth/hooks/useAuth";
enum XHRFailureCodes {
AUTHENTICATION_REQUIRED = 'AUTHENTICATION_REQUIRED',
UNAUTHORIZED_ACTION = 'UNAUTHORIZED_ACTION',
FORM_VALIDATION_FAILED = 'FORM_VALIDATION_FAILED',
MISSING_REQUIRED_PARAMETERS = 'MISSING_REQUIRED_PARAMETERS',
NO_RESULTS_FOUND = 'NO_RESULTS_FOUND',
RATE_LIMIT_EXCEEDED = 'RATE_LIMIT_EXCEEDED',
UNKNOWN_ERROR = 'UNKNOWN_ERROR',
ACTION_FAILED = 'ACTION_FAILED',
}
async function useGetApi(url:string){
const { setIsAuthenticated } = useAuth();
const response = await fetch(url, {
method: 'GET',
credentials: 'include',
});
const api = await response.json();
if(api.success === false){
if(api.error_type === XHRFailureCodes.AUTHENTICATION_REQUIRED){
console.log('AUTHENTICATION_REQUIRED');
setIsAuthenticated(false);
}
}
return api;
}
async function getApi(url:string){
const response = await fetch(url, {
method: 'GET',
credentials: 'include',
});
const api = await response.json();
if(api.success === false){
if(api.error_type === XHRFailureCodes.AUTHENTICATION_REQUIRED){
console.log('AUTHENTICATION_REQUIRED');
// TODO: maybe set the login context to not authenticated, triggering the login modal to appear
}
}
return api;
}
export { getApi, useGetApi, XHRFailureCodes };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment