Skip to content

Commit

Permalink
feat: added date filters
Browse files Browse the repository at this point in the history
  • Loading branch information
Opty1712 committed Jul 31, 2022
1 parent 4d19b3e commit eb0a0d9
Show file tree
Hide file tree
Showing 9 changed files with 233 additions and 50 deletions.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
"typescript": "^4.2.4"
},
"dependencies": {
"@date-io/date-fns": "1.x",
"@emotion/css": "^11.10.0",
"@emotion/react": "^11.9.3",
"@emotion/server": "^11.4.0",
Expand All @@ -79,8 +80,10 @@
"@mui/icons-material": "^5.8.4",
"@mui/material": "^5.9.2",
"@mui/x-data-grid": "^5.15.0",
"@mui/x-date-pickers": "^5.0.0-beta.3",
"@walletconnect/web3-provider": "^1.7.8",
"bignumber.js": "^9.0.2",
"date-fns": "^2.29.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"web3": "^1.7.4",
Expand Down
26 changes: 23 additions & 3 deletions src/containers/Container.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,16 @@ import { useSearch } from './useSearch';

export const NFTContainer = () => {
const { account } = useAccount();
const { search, setSearch, searchResults, isLoading } = useSearch(account);
const {
search,
setSearch,
searchResults,
isLoading,
fromDate,
setFromDate,
setToDate,
toDate
} = useSearch(account);

return (
<Box
Expand All @@ -25,11 +34,22 @@ export const NFTContainer = () => {
margin: '0 40px'
}}
>
{account ? <Search search={search} setSearch={setSearch} /> : <div />}
{account ? (
<Search
search={search}
setSearch={setSearch}
fromDate={fromDate}
setFromDate={setFromDate}
toDate={toDate}
setToDate={setToDate}
/>
) : (
<div />
)}
<Wallet />
</Box>

{account && search ? (
{account && search.length > 2 ? (
<Box
style={{
width: 'calc(100% - 80px)',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { css } from '@emotion/css';
import { Box, Typography } from '@mui/material';
import { DataGrid, GridColDef, GridRenderCellParams } from '@mui/x-data-grid';
import { memo, ReactNode } from 'react';
import { NFTItem } from '../../types';
import { NFTItem } from '../types';

type ResultsProps = {
result: Array<NFTItem>;
Expand All @@ -12,7 +12,7 @@ type ResultsProps = {
export const Results = memo<ResultsProps>(({ result, isLoading }) => {
if (isLoading) {
return (
<Box>
<Box style={{ padding: '20px' }}>
<Typography variant="h4" color="#1976d2">
Loading...
</Typography>
Expand Down
1 change: 0 additions & 1 deletion src/containers/components/Results/index.ts

This file was deleted.

88 changes: 61 additions & 27 deletions src/containers/components/Search.tsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,70 @@
import { Box, TextField } from '@mui/material';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { ChangeEventHandler, memo, useCallback } from 'react';

type SearchParams = {
search: string;
setSearch: (search: string) => void;
fromDate: Date;
setFromDate: (fromDate: Date) => void;
toDate: Date;
setToDate: (toDate: Date) => void;
};
export const Search = memo<SearchParams>(({ search, setSearch }) => {
const handleSearch = useCallback<ChangeEventHandler<HTMLInputElement>>(
(event) => {
setSearch(event.target.value);
},
[setSearch]
);
export const Search = memo<SearchParams>(
({ search, setSearch, fromDate, setFromDate, setToDate, toDate }) => {
const handleSearch = useCallback<ChangeEventHandler<HTMLInputElement>>(
(event) => {
setSearch(event.target.value);
},
[setSearch]
);

return (
<Box
style={{
background: '#fff',
borderRadius: '5px',
padding: '20px',
boxSizing: 'border-box',
width: '100%',
maxWidth: '50%'
}}
>
<TextField
onChange={handleSearch}
value={search}
placeholder="Search for NFT"
fullWidth={true}
/>
</Box>
);
});
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<Box
style={{
background: '#fff',
borderRadius: '5px',
padding: '20px',
boxSizing: 'border-box',
width: '100%',
maxWidth: '50%'
}}
>
<TextField
label="Name"
onChange={handleSearch}
value={search}
placeholder="Search for NFT"
fullWidth={true}
style={{
marginBottom: '20px'
}}
/>
<div style={{ display: ' flex', justifyContent: 'space-between' }}>
<DatePicker
label="From Date"
value={fromDate}
onChange={(newValue) => {
setFromDate(newValue || new Date());
}}
renderInput={(params) => <TextField {...params} />}
/>
<div style={{ width: '20px' }} />
<DatePicker
label="To Date"
value={toDate}
onChange={(newValue) => {
setToDate(newValue || new Date());
}}
renderInput={(params) => <TextField {...params} />}
/>
</div>
</Box>
</LocalizationProvider>
);
}
);
Search.displayName = nameof(Search);
6 changes: 4 additions & 2 deletions src/containers/components/Wallet/Wallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const Wallet = memo(() => {
{account ? (
<Box
style={{
display: 'inline-block',
display: 'flex',
marginLeft: '40px'
}}
>
Expand All @@ -31,14 +31,15 @@ export const Wallet = memo(() => {
startIcon={<LogoutIcon />}
onClick={disconnectWallet}
variant="contained"
size="large"
>
Disconnect {formatAddress(account)}
</Button>
{Object.entries(balance || {}).map(([key, value]) => (
<div
key={key}
style={{
padding: '10px 13px'
padding: '15px 20px'
}}
>
<PixIcon
Expand All @@ -59,6 +60,7 @@ export const Wallet = memo(() => {
<Button
onClick={connectWallet}
variant="contained"
size="large"
startIcon={<AccountBalanceWalletIcon />}
>
Connect Wallet
Expand Down
3 changes: 2 additions & 1 deletion src/containers/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ export type MetaDataJSON = {
animation_url?: string;
};

export type NFTItem = Omit<APIItem, 'metadata'> & MetaDataJSON & { id: string };
export type NFTItem = Omit<APIItem, 'metadata'> &
MetaDataJSON & { id: string; price?: string };
79 changes: 65 additions & 14 deletions src/containers/useSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,36 @@ import { APIItem, MetaDataJSON, NFTItem } from './types';

export const useSearch = (account: string | null) => {
const [search, setSearch] = useState('');

const [fromDate, setFromDate] = useState<Date>(() => {
const date = new Date();
date.setFullYear(date.getFullYear() - 1);

return date;
});

const [toDate, setToDate] = useState<Date>(new Date());
const { isSwitchedOn, switchOff, switchOn } = useSwitcher();
const [searchResults, setSearchResults] = useState<Array<NFTItem>>([]);

const handleFetch = useCallback(async () => {
if (search.length < 3) {
return;
}

switchOn();

await fetchTokens()
fetchTokens({
q: search,
from_date: fromDate.toISOString(),
to_date: toDate.toISOString()
})
.then((result) => {
setSearchResults(extractTokens(result.result));
})
.catch((error) => console.error(error))
.finally(switchOff);
}, [switchOff, switchOn]);
}, [fromDate, search, switchOff, switchOn, toDate]);

useEffect(() => {
if (!account) {
Expand All @@ -26,7 +43,16 @@ export const useSearch = (account: string | null) => {
handleFetch();
}, [search, account, handleFetch]);

return { search, setSearch, searchResults, isLoading: isSwitchedOn };
return {
search,
setSearch,
searchResults,
isLoading: isSwitchedOn,
fromDate,
toDate,
setFromDate,
setToDate
};
};

type APIAnswer = {
Expand All @@ -36,9 +62,18 @@ type APIAnswer = {
total: number;
};

function fetchTokens<T = APIAnswer>(): Promise<T> {
return fetch(
'https://deep-index.moralis.io/api/v2/nft/search?chain=eth&format=decimal&filter=name&q=star',
type FetchTokensParams = {
q: string;
from_date?: string;
to_date?: string;
};
async function fetchTokens<T = APIAnswer>(
params: FetchTokensParams
): Promise<T> {
const response = await fetch(
`https://deep-index.moralis.io/api/v2/nft/search?chain=eth&format=decimal&filter=name&${buildQuery(
params
)}`,
{
method: 'GET',
headers: {
Expand All @@ -47,13 +82,12 @@ function fetchTokens<T = APIAnswer>(): Promise<T> {
'jbWrgmADlNz72pcGr6o1MUIqakKZUsUrrap4kiliJsYpwIvcZ7J8025hqSZBcgUW'
}
}
).then((response) => {
if (!response.ok) {
throw new Error(response.statusText);
}
);
if (!response.ok) {
throw new Error(response.statusText);
}

return response.json() as Promise<T>;
});
return await (response.json() as Promise<T>);
}

const checkIsMetaDataExists = (value: unknown): value is MetaDataJSON =>
Expand All @@ -76,18 +110,35 @@ const extractTokens = (tokens: Array<APIItem>): Array<NFTItem> => {
? metadataJSON[item] || ''
: '';

token[item] = convertIPFSURL(value);
token[item] = convertIPFSToURL(value);
});
}

return token;
});
};

const convertIPFSURL = (url: string) => {
const convertIPFSToURL = (url: string) => {
if (url.startsWith('')) {
return url.replace('ipfs://', 'https://ipfs.io/ipfs/');
}

return url;
};

const buildQuery = (args: FetchTokensParams): string => {
const queryArray = getKeys(args).reduce<Array<string | number>>(
(accumulator, key) => {
const value = args[key];

if (typeof value === 'string' || typeof value === 'number') {
accumulator.push(`${key}=${value}`);
}

return accumulator;
},
[]
);

return queryArray.join('&');
};
Loading

0 comments on commit eb0a0d9

Please sign in to comment.