Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

posts.tsx

50 lines1.1 KB

1import axios from 'redaxios'
2​
3async function loaderDelayFn<T>(fn: (...args: Array<any>) => Promise<T> | T) {
4 const delay = Number(sessionStorage.getItem('loaderDelay') ?? 0)
5 const delayPromise = new Promise((r) => setTimeout(r, delay))
6​
7 await delayPromise
8 const res = await fn()
9​
10 return res
12​
13type Invoice = {
14 id: number
15 title: string
16 body: string
18​
19let invoices: Array<Invoice> = null!
20​
21let invoicesPromise: Promise<void> | undefined = undefined
22​
23const ensureInvoices = async () => {
24 if (!invoicesPromise) {
25 invoicesPromise = Promise.resolve().then(async () => {
26 const { data } = await axios.get(
27 'https://jsonplaceholder.typicode.com/posts',
28 )
29 invoices = data.slice(0, 10)
30 })
31 }
32​
33 await invoicesPromise
35​
36export async function fetchInvoices() {
37 return loaderDelayFn(() => ensureInvoices().then(() => invoices))
39​
40export async function fetchInvoiceById(id: number) {
41 return loaderDelayFn(() =>
42 ensureInvoices().then(() => {
43 const invoice = invoices.find((d) => d.id === id)
44 if (!invoice) {
45 throw new Error('Invoice not found')
46 }
47 return invoice
48 }),
49 )