Skip to content

Commit

Permalink
feat: replaced all fetch requests with axios requests
Browse files Browse the repository at this point in the history
  • Loading branch information
olwalkey committed Jan 19, 2025
1 parent c831b01 commit 2150c82
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 63 deletions.
19 changes: 4 additions & 15 deletions resources/scripts/components/server/modrinth/DisplayMods.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import axios from 'axios';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

Expand Down Expand Up @@ -37,6 +38,7 @@ const ProjectSelector: React.FC<Props> = ({ appVersion, baseUrl, nonApiUrl }) =>
const [isModalVisible, setModalVisible] = useState(false);

const uuid = ServerContext.useStoreState((state) => state.server.data!);

const fetchProjects = async () => {
setIsLoading(true); // Start loading
try {
Expand All @@ -48,39 +50,26 @@ const ProjectSelector: React.FC<Props> = ({ appVersion, baseUrl, nonApiUrl }) =>
: ['project_type:mod'],
].filter(Boolean);

// console.log('Constructed facets:', facets);

const searchParams = new URLSearchParams({
facets: JSON.stringify(facets),
index: 'relevance',
offset: `${offset}`,
});
const query = settings.searchTerms.replace(/ /g, '-');
const apiUrl = `${baseUrl}${apiEndpoints.projects}?${searchParams.toString()}&query=${query}`;
// console.log('Constructed API URL:', apiUrl);

const response = await fetch(apiUrl, {
const response = await axios.get(apiUrl, {
headers: {
'Content-Type': 'application/json',
'User-Agent': `pyrohost/pyrodactyl/${appVersion} (pyro.host)`,
},
});

// console.log('Response status:', response.status);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

const data = await response.json();
// console.log('Fetched projects data:', data);

const updatedProjects = data.hits.map((project: Project) => ({
const updatedProjects = response.data.hits.map((project: Project) => ({
...project,
icon_url: project.icon_url || 'N/A',
}));

// console.log(uuid);

setProjects(updatedProjects);
} catch (error) {
toast.error('Failed to fetch projects.');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { faDownload } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import axios from 'axios';
import { useEffect, useState } from 'react';

import FlashMessageRender from '@/components/FlashMessageRender';
Expand Down Expand Up @@ -29,10 +30,10 @@ const DownloadModModal = ({ modid, modName }: Props) => {
// Fetch mod versions from Modrinth API
useEffect(() => {
setLoading(true);
fetch(`https://api.modrinth.com/v2/project/${modid}/version`)
.then((response) => response.json())
.then((data) => {
setVersions(data);
axios
.get(`https://api.modrinth.com/v2/project/${modid}/version`)
.then((response) => {
setVersions(response.data);
setLoading(false);
})
.catch(() => setLoading(false));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const EnvironmentSelector: React.FC<Props> = ({ items, onSelectionChange }) => {
setSelectedItems((prev) => {
const updatedItems = prev.includes(item) ? prev.filter((i) => i !== item) : [...prev, item];

onSelectionChange(updatedItems); // Notify parent about the changes
onSelectionChange(updatedItems);
return updatedItems;
});
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';

import { ScrollMenu } from '@/components/elements/ScrollMenu';
import Checkbox from '@/components/elements/inputs/Checkbox';

import { apiEndpoints, fetchHeaders, gameLoaders, settings } from './config';
import { fetchNewProjects } from './config';
import { apiEndpoints, fetchHeaders, settings } from './config';

interface GameVersion {
version: string;
Expand All @@ -20,62 +19,80 @@ interface Props {
const GameVersionSelector: React.FC<Props> = ({ appVersion, baseUrl }) => {
const [minecraftVersions, setMinecraftVersions] = useState<GameVersion[]>([]);
const [isSnapshotSelected, setIsSnapshotSelected] = useState<boolean>(false);
const [isLoading, setIsLoading] = useState<boolean>(false);

const apiUrl = `${baseUrl}${apiEndpoints.versions}`;

useEffect(() => {
async function fetchGameVersions() {
const fetchGameVersions = async () => {
setIsLoading(true);
try {
const response = await fetch(apiUrl, {
headers: fetchHeaders(appVersion),
});

if (!response.ok) {
throw new Error(`Failed to fetch versions: ${response.statusText}`);
}

const data = await response.json();
setMinecraftVersions(data);
if (Array.isArray(data)) {
setMinecraftVersions(data);
} else {
throw new Error('Invalid data format received from API.');
}
} catch (error) {
toast.error('Failed to fetch Minecraft versions.');
console.error(error);
} finally {
setIsLoading(false);
}
}
};

if (appVersion) {
fetchGameVersions();
}
}, [appVersion]);

const filteredVersions = minecraftVersions.filter((version) => {
if (isSnapshotSelected) {
return version.version_type === 'snapshot';
} else {
return version.version_type !== 'snapshot';
}
});
const filteredVersions = useMemo(() => {
return minecraftVersions.filter((version) =>
isSnapshotSelected ? version.version_type === 'snapshot' : version.version_type === 'release',
);
}, [minecraftVersions, isSnapshotSelected]);

const handleSelectionChange = (selectedItems: string[]) => {
settings.versions = selectedItems;
console.log('Updated settings.versions:', settings.versions);
};

const handleSnapshotToggle = () => {
setIsSnapshotSelected((prev) => !prev);
};

return (
<div>
{filteredVersions.length > 0 ? (
<ScrollMenu
items={filteredVersions.map((version) => version.version)}
onSelectionChange={handleSelectionChange}
/>
) : (
<p>No versions available...</p>
)}
{filteredVersions.length > 0 ? (
<div className='mb-4'>
<Checkbox
label='Show Snapshots'
checked={isSnapshotSelected}
onChange={() => setIsSnapshotSelected((prev) => !prev)}
onClick={fetchNewProjects()}
/>
</div>
{isLoading ? (
<p>Loading versions...</p>
) : (
<p></p>
<>
{filteredVersions.length > 0 ? (
<>
<ScrollMenu
items={filteredVersions.map((version) => version.version)}
onSelectionChange={handleSelectionChange}
/>
<div className='mb-4'>
<Checkbox
label='Show Snapshots'
checked={isSnapshotSelected}
onChange={handleSnapshotToggle}
/>
</div>
</>
) : (
<p>No versions found</p>
)}
</>
)}
</div>
);
Expand Down
21 changes: 9 additions & 12 deletions resources/scripts/components/server/modrinth/LoaderSelector.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import axios from 'axios';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

import EnvironmentSelector from './EnvironmentSelector';
import { apiEndpoints, fetchNewProjects, settings } from './config';

interface GameLoaders {
icon: string; // SVG data (probably won't use this)
icon: string;
name: string;
supported_project_types: string[];
}
Expand All @@ -23,23 +24,20 @@ const LoaderSelector: React.FC<Props> = ({ appVersion, baseUrl }) => {
useEffect(() => {
async function fetchLoaders() {
try {
const response = await fetch(apiUrl, {
const { data } = await axios.get(apiUrl, {
headers: {
'Content-Type': 'application/json',
'User-Agent': `pyrohost/pyrodactyl/${appVersion} (pyro.host)`,
},
});

if (!response.ok) {
toast(`HTTP Error! Status: ${response.status}`);
throw new Error(`HTTP error! Status: ${response.status}`);
}

const data = await response.json();

setLoaders(data);
} catch (error) {
toast.error('Failed to fetch game loaders.');
} catch (error: any) {
if (error.response) {
toast(`HTTP Error! Status: ${error.response.status}`);
} else {
toast.error('Failed to fetch game loaders.');
}
console.error(error);
}
}
Expand All @@ -51,7 +49,6 @@ const LoaderSelector: React.FC<Props> = ({ appVersion, baseUrl }) => {

const handleSelectionChange = (selectedItems: string[]) => {
settings.loaders = selectedItems;
// fetchProjectsGlobal(baseUrl, appVersion);
console.log('Selected loaders updated:', selectedItems);
};

Expand Down

0 comments on commit 2150c82

Please sign in to comment.