-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJobBoard.tsx
More file actions
109 lines (98 loc) · 2.67 KB
/
Copy pathJobBoard.tsx
File metadata and controls
109 lines (98 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { useState, useEffect, type ReactNode } from 'react';
import './JobBoard.css';
interface Job {
id: number;
url: string;
title: string;
by: string;
time: number;
}
const MAX_JOBS = 6;
export default function JobBoard() {
const [jobIds, setJobIds] = useState([]);
const [cursor, setCursor] = useState(MAX_JOBS);
const [jobs, setJobs] = useState<Job[]>([]);
useEffect(() => {
async function getJobIds() {
try {
const result = await fetch("https://hacker-news.firebaseio.com/v0/jobstories.json");
if (result.status === 200) {
const json = await result.json();
setJobIds(json);
}
} catch (e) {
console.error(e);
}
}
getJobIds();
}, []);
useEffect(() => {
if (jobIds.length === 0) return;
updateJobs();
}, [jobIds, cursor]);
async function updateJob(jid: number) {
try {
const result = await fetch(`https://hacker-news.firebaseio.com/v0/item/${jid}.json`);
if (result.status === 200) {
const json = await result.json();
return json;
}
} catch (e) {
console.error(e);
}
return 0;
}
function updateCursor() {
if (cursor + MAX_JOBS >= jobIds.length) {
setCursor(jobIds.length);
} else {
setCursor(cursor + MAX_JOBS);
}
}
async function updateJobs() {
const start = jobs.length; // Only fetch jobs not already loaded
const end = Math.min(cursor, jobIds.length);
const newJobs: Job[] = [];
for (let jid = start; jid < end; jid++) {
const job = await updateJob(jobIds[jid]);
if (job && job.id) newJobs.push(job);
}
setJobs(prevJobs => [...prevJobs, ...newJobs]);
}
function OneJob({ job }: { job: Job }) {
if (!job || !job.title) return null;
return (
<div className="job">
<a href={job.url} target="_blank" rel="noopener noreferrer">
<div className="jobTitle">{job.title}</div>
</a>
<div>
By {job.by} • {new Date(job.time * 1000).toDateString()}
</div>
</div>
);
}
function Jobs({ jobs }: { jobs: Job[] }): ReactNode {
return <div className='jobs'>
{jobs.map(job => <OneJob key={job.id} job={job} />)}
</div>
}
return (
<div className='job-board'>
<h1 className="message">Hacker News Jobs Board</h1>
{jobs.length === 0 ? <div>Loading...</div> : <>
<Jobs jobs={jobs} />
<div>
<button
style={{ display: jobs.length >= jobIds.length ? "none" : "block" }}
onClick={() => {
updateCursor();
}}
>
Load more
</button>
</div>
</>}
</div>
);
}