Skip to content

Commit

Permalink
create page that can make universalis requests
Browse files Browse the repository at this point in the history
  • Loading branch information
cohenaj194 committed Jul 7, 2024
1 parent 1db6374 commit 30de330
Showing 1 changed file with 177 additions and 13 deletions.
190 changes: 177 additions & 13 deletions app/routes/ffxiv.extended-history.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,178 @@
const Foobar = () => {
import { useActionData, useNavigation } from '@remix-run/react';
import type { ActionFunction } from '@remix-run/cloudflare';
import { json } from '@remix-run/cloudflare';
import NoResults from '~/components/Common/NoResults';
import { getUserSessionData } from '~/sessions';
import ItemSelect from '~/components/Common/ItemSelect';
import type { ItemSelected } from '~/components/Common/ItemSelect';
import { useEffect, useState } from 'react';
import SmallFormContainer from '~/components/form/SmallFormContainer';
import SmallTable from '~/components/WoWResults/FullScan/SmallTable';
import { PageWrapper, TitleH2 } from '~/components/Common';
import { useDispatch } from 'react-redux';
import { setItemHistory } from '~/redux/reducers/queriesSlice';
import { useTypedSelector } from '~/redux/useTypedSelector';
import { getItemNameById } from '~/utils/items';

// Overwrite default meta in the root.tsx
export const meta: MetaFunction = () => {
return {
charset: 'utf-8',
viewport: 'width=device-width,initial-scale=1',
title: 'Saddlebag Exchange: FFXIV Full Sale History',
description: 'Saddlebag Exchange: FFXIV sale history on past 1800 sales',
};
};

export const links: LinksFunction = () => [
{
rel: 'canonical',
href: 'https://saddlebagexchange.com/ffxiv/extended-history',
},
];

const validateInput = ({
itemId,
world,
}: {
itemId?: FormDataEntryValue | null;
world?: FormDataEntryValue | null;
}): { itemId: number; world: string } | { exception: string } => {
if (itemId === undefined || itemId === null) {
return { exception: 'Item not found' };
}

if (world === undefined || world === null) {
return { exception: 'World not set' };
}

if (typeof itemId !== 'string') {
return { exception: 'Invalid item' };
}

if (typeof world !== 'string') {
return { exception: 'Invalid world' };
}

const parsedItemId = parseInt(itemId);

if (isNaN(parsedItemId)) return { exception: 'Invalid item' };

return { itemId: parsedItemId, world };
};

export const action: ActionFunction = async ({ request }) => {
const formData = await request.formData();
const session = await getUserSessionData(request);

formData.append('world', session.getWorld());

const validInput = validateInput({
itemId: formData.get('itemId'),
world: formData.get('world'),
});

if ('exception' in validInput) {
return validInput;
}

try {
const response = await fetch(`https://universalis.app/api/v2/history/${validInput.world}/${validInput.itemId}`);
const data = await response.json();
console.log(data);

if (!data.entries) {
return json({ exception: 'No entries found.' });
}

return json({ entries: data.entries, payload: validInput });
} catch (err) {
console.error('Error fetching data:', err);
return { exception: 'Error fetching data.' };
}
};

const parseServerError = (error: string) => {
if (error.includes('Error fetching data:')) {
return 'Failed to receive result from external API';
}

return error;
};

const FFXIVSaleHistory = () => {
const transition = useNavigation();
const results = useActionData();
const [formState, setFormState] = useState<ItemSelected | undefined>();
const [error, setError] = useState<string | undefined>();
const { darkmode } = useTypedSelector((state) => state.user);
const { itemHistory } = useTypedSelector((state) => state.queries);
const dispatch = useDispatch();

const onSubmit = (e: React.MouseEvent<HTMLButtonElement>) => {
if (transition.state === 'submitting' || !formState) {
e.preventDefault();
return;
}
};

useEffect(() => {
if (results && results.entries) {
dispatch(setItemHistory(results));
} else if (results && results.exception) {
const message = parseServerError(results.exception);
setError(`Server Error: ${message}`);
} else if (results && results.payload) {
setError('No results found');
}
}, [results, dispatch]);

const resultTitle = itemHistory ? getItemNameById(itemHistory.payload.itemId) : null;

const handleFormChange = (selectValue?: ItemSelected | undefined) => {
if (error) {
setError(undefined);
}
setFormState(selectValue);
};

const handleTextChange = () => {
setError(undefined);
};

return (
<div className={`m-12`}>
<main className="flex-1">
<h2 className={`text-2xl`}>Foobar</h2>
<p className={`text-prose`}>
Foobar
</p>
</main>
</div>
)
}

export default Foobar
<PageWrapper>
<>
<div className="py-3">
<SmallFormContainer
title="Find Sale History"
onClick={onSubmit}
error={error}
loading={transition.state === 'submitting'}
disabled={!formState}
>
<>
<ItemSelect
onSelectChange={handleFormChange}
onTextChange={handleTextChange}
/>
</>
</SmallFormContainer>
</div>
{error === 'No results found' && !itemHistory && (
<NoResults href={`/ffxiv-sale-history`} />
)}
{resultTitle && (
<div className="max-w-4xl mx-auto px-4">
<TitleH2 title={resultTitle} />
</div>
)}
{itemHistory && itemHistory.entries && (
<SmallTable data={itemHistory.entries} darkMode={darkmode} />
)}
</>
</PageWrapper>
);
};

export default FFXIVSaleHistory;

0 comments on commit 30de330

Please sign in to comment.