Add schedule loader

This commit is contained in:
Vencislav Atanasov 2024-09-18 21:24:35 +03:00
parent e87e4b9502
commit 1b14b697c9
7 changed files with 61 additions and 8 deletions

1
.env Normal file
View File

@ -0,0 +1 @@
VITE_CFP_BASE_URL=http://cfp.localhost/api/conferences/

View File

@ -1,11 +1,8 @@
import './App.css';
import ScheduleLoader from './ScheduleLoader.jsx';
function App() {
return (
<>
</>
);
return (<ScheduleLoader/>);
}
export default App;

21
src/ScheduleLoader.jsx Normal file
View File

@ -0,0 +1,21 @@
import useConferences from './hooks/useConferences.js';
export default function ScheduleLoader() {
const {
conferences,
error,
isLoading,
} = useConferences();
return (<>
{isLoading && <p>Please wait...</p>}
{error && <p>Error: {error}</p>}
{conferences && <>
<label>Select a conference</label>
<select>
{conferences.map(conference => <option key={conference.id}
value={conference.id}>{conference.title}</option>)}
</select>
</>}
</>);
}

View File

@ -0,0 +1,7 @@
import useSWR from 'swr';
const fetcher = (...args) => fetch(...args).then(res => res.json());
export default function useCfpRequest(path = '') {
return useSWR(import.meta.env.VITE_CFP_BASE_URL.concat(path), fetcher);
}

View File

@ -0,0 +1,17 @@
import useCfpRequest from './useCfpRequest.js';
import { useMemo } from 'react';
import { dateSorter } from '../utils.js';
export default function useConferences() {
const {
data,
...rest
} = useCfpRequest();
const conferences = useMemo(() => Array.isArray(data) ? data.sort(dateSorter('start_date')) : data, [data]);
return {
conferences,
...rest,
};
}

View File

@ -4,7 +4,7 @@ import App from './App.jsx';
import './index.css';
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
<StrictMode>
<App />
</StrictMode>,
);

10
src/utils.js Normal file
View File

@ -0,0 +1,10 @@
function sorter(a, b, fieldFn) {
const fieldA = fieldFn(a);
const fieldB = fieldFn(b);
return fieldA === fieldB ? 0 : (
fieldA < fieldB ? -1 : 1
);
}
export const dateSorter = key => (a, b) => sorter(a, b, item => Date.parse(item[key]));