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

mocks.ts

37 lines880 Bytes

1import { HttpResponse, delay, http } from 'msw'
2import { setupWorker } from 'msw/browser'
3​
4const storageKey = 'auto-refetching-list'
5​
6const getList = (): Array<string> =>
7 JSON.parse(localStorage.getItem(storageKey) ?? 'null') ?? [
8 'Item 1',
9 'Item 2',
10 'Item 3',
11 ]
12​
13const setList = (list: Array<string>) =>
14 localStorage.setItem(storageKey, JSON.stringify(list))
15​
16// an simple endpoint for getting current list
17export const worker = setupWorker(
18 http.get('/api/data', async ({ request }) => {
19 const { searchParams } = new URL(request.url)
20 const add = searchParams.get('add')
21 const clear = searchParams.get('clear')
22​
23 const list = getList()
24​
25 if (add) {
26 if (!list.includes(add)) {
27 setList([...list, add])
28 }
29 } else if (clear) {
30 setList([])
31 }
32​
33 await delay(100)
34​
35 return HttpResponse.json(getList())
36 }),