Refactor
This commit is contained in:
47
src/hooks/helpers.ts
Normal file
47
src/hooks/helpers.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
export function date(isMobile: boolean) {
|
||||
const currentDate = new Date();
|
||||
const dateOptions: Intl.DateTimeFormatOptions = !isMobile
|
||||
? {
|
||||
weekday: 'long',
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
}
|
||||
: {};
|
||||
const date = currentDate.toLocaleDateString('en-US', dateOptions);
|
||||
return date;
|
||||
}
|
||||
export function greet(list: any) {
|
||||
const currentTime = new Date();
|
||||
const greet = Math.floor(currentTime.getHours() / 6);
|
||||
const easterEggChance = Math.floor(Math.random() * 100);
|
||||
let timeBased: any = [];
|
||||
let customGreetings: any = [];
|
||||
for (const l of list) {
|
||||
if (l.customGreeting === 0) {
|
||||
timeBased = timeBased.concat(l);
|
||||
} else {
|
||||
customGreetings = customGreetings.concat(l);
|
||||
}
|
||||
}
|
||||
if (easterEggChance > 10 || customGreetings.length === 0) {
|
||||
return timeBased[greet].message;
|
||||
}
|
||||
return customGreetings[Math.floor(Math.random() * customGreetings.length)].message;
|
||||
}
|
||||
export function validURL(str: any) {
|
||||
const pattern = new RegExp(
|
||||
'^(https?:\\/\\/)?' + // protocol
|
||||
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
|
||||
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
|
||||
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
|
||||
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
|
||||
'(\\#[-a-z\\d_]*)?$',
|
||||
'i',
|
||||
); // fragment locator
|
||||
return !!pattern.test(str);
|
||||
}
|
||||
export function containsProtocol(str: any) {
|
||||
const pattern = /^(https?:\/\/).*/i;
|
||||
return !!pattern.test(str);
|
||||
}
|
||||
@@ -1 +1,3 @@
|
||||
export { useQueryAPI, useWeatherAPI } from './useAPI';
|
||||
export { useQueryAPI, useWeatherAPI, useMutationAPI } from './useAPI';
|
||||
export { date, greet } from './helpers';
|
||||
export { validURL, containsProtocol } from './helpers';
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
import {
|
||||
useInfiniteQuery,
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from '@tanstack/react-query';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useCallback } from 'react';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
@@ -48,19 +43,7 @@ export function useWeatherAPI({ endpoint }: { endpoint: string }) {
|
||||
} else if (endpoint === 'hourly') {
|
||||
url = 'https://api.weather.gov/gridpoints/HGX/55,96/forecast/hourly';
|
||||
}
|
||||
const callEndpoint = async (endpoint: string) => {
|
||||
const options: object = {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/geo+json',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': '*',
|
||||
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
|
||||
'Access-Control-Allow-Credentials': true,
|
||||
'Sec-Fetch-Mode': 'no-cors',
|
||||
'Sec-Fetch-Site': 'same-site',
|
||||
},
|
||||
};
|
||||
const callEndpoint = async () => {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`${response.status} ${response.statusText}`);
|
||||
@@ -70,7 +53,7 @@ export function useWeatherAPI({ endpoint }: { endpoint: string }) {
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['GET', url],
|
||||
queryFn: () => callEndpoint(endpoint),
|
||||
queryFn: () => callEndpoint(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -343,89 +326,8 @@ interface DownloadFileOptions {
|
||||
}
|
||||
|
||||
export function useDownloadFile() {
|
||||
const downloadFile = useCallback(
|
||||
async ({ endpoint, file_name }: DownloadFileOptions) => {
|
||||
const options: any = {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': '*',
|
||||
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
|
||||
'Access-Control-Allow-Credentials': true,
|
||||
'Sec-Fetch-Mode': 'no-cors',
|
||||
'Sec-Fetch-Site': 'same-site',
|
||||
},
|
||||
};
|
||||
const toastID = toast.loading('Processing...');
|
||||
try {
|
||||
const response = await fetch(url, options);
|
||||
if (!response.ok) {
|
||||
throw new Error('Network response was not ok');
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
if (blob.type === 'application/json') {
|
||||
const blob_text = await blob.text();
|
||||
const cleaned_text = blob_text.replace(/"/g, '');
|
||||
toast.update(toastID, {
|
||||
render: cleaned_text,
|
||||
type: 'info',
|
||||
isLoading: false,
|
||||
autoClose: 5000,
|
||||
closeButton: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
const blobURL = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
|
||||
a.style.display = 'none';
|
||||
a.href = blobURL;
|
||||
a.download = file_name;
|
||||
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(blobURL);
|
||||
document.body.removeChild(a);
|
||||
toast.update(toastID, {
|
||||
render: `${file_name} Downloaded`,
|
||||
type: 'success',
|
||||
isLoading: false,
|
||||
autoClose: 5000,
|
||||
closeButton: null,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Download failed:', error);
|
||||
toast.update(toastID, {
|
||||
render: `Error Downloading ${file_name}. Please try again.`,
|
||||
type: 'error',
|
||||
isLoading: false,
|
||||
autoClose: 5000,
|
||||
closeButton: null,
|
||||
});
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return downloadFile;
|
||||
}
|
||||
|
||||
export const useFetchInfiniteQuery = ({
|
||||
endpoint,
|
||||
pageSize = 10,
|
||||
}: {
|
||||
endpoint: string;
|
||||
pageSize?: number;
|
||||
}) => {
|
||||
const queryKey = ['GET', endpoint];
|
||||
|
||||
const fetchInfiniteQuery = async (endpoint: string) => {
|
||||
const requestOptions: any = {
|
||||
const downloadFile = useCallback(async ({ file_name }: DownloadFileOptions) => {
|
||||
const options: any = {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -437,35 +339,58 @@ export const useFetchInfiniteQuery = ({
|
||||
'Sec-Fetch-Site': 'same-site',
|
||||
},
|
||||
};
|
||||
const toastID = toast.loading('Processing...');
|
||||
try {
|
||||
const response = await fetch(url, requestOptions);
|
||||
return await response.json();
|
||||
const response = await fetch(url, options);
|
||||
if (!response.ok) {
|
||||
throw new Error('Network response was not ok');
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
if (blob.type === 'application/json') {
|
||||
const blob_text = await blob.text();
|
||||
const cleaned_text = blob_text.replace(/"/g, '');
|
||||
toast.update(toastID, {
|
||||
render: cleaned_text,
|
||||
type: 'info',
|
||||
isLoading: false,
|
||||
autoClose: 5000,
|
||||
closeButton: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
const blobURL = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
|
||||
a.style.display = 'none';
|
||||
a.href = blobURL;
|
||||
a.download = file_name;
|
||||
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(blobURL);
|
||||
document.body.removeChild(a);
|
||||
toast.update(toastID, {
|
||||
render: `${file_name} Downloaded`,
|
||||
type: 'success',
|
||||
isLoading: false,
|
||||
autoClose: 5000,
|
||||
closeButton: null,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching transactions:', error);
|
||||
throw error;
|
||||
console.error('Download failed:', error);
|
||||
toast.update(toastID, {
|
||||
render: `Error Downloading ${file_name}. Please try again.`,
|
||||
type: 'error',
|
||||
isLoading: false,
|
||||
autoClose: 5000,
|
||||
closeButton: null,
|
||||
});
|
||||
}
|
||||
};
|
||||
const queryFn = ({ pageParam = 1 }) =>
|
||||
fetchInfiniteQuery(`${endpoint}&page=${pageParam}&size=${pageSize}`);
|
||||
const getNextPageParam = (lastPage: any, allPages: any) => {
|
||||
if (lastPage.items.length < pageSize) {
|
||||
return undefined;
|
||||
}
|
||||
return allPages.length + 1;
|
||||
};
|
||||
const { data, isLoading, isFetchingNextPage, fetchNextPage, isError, isFetching } =
|
||||
useInfiniteQuery({
|
||||
queryKey,
|
||||
queryFn,
|
||||
getNextPageParam,
|
||||
initialPageParam: 1,
|
||||
});
|
||||
return {
|
||||
data,
|
||||
isLoading,
|
||||
isFetchingNextPage,
|
||||
fetchNextPage,
|
||||
isError,
|
||||
isFetching,
|
||||
};
|
||||
};
|
||||
}, []);
|
||||
|
||||
return downloadFile;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user