-
Notifications
You must be signed in to change notification settings - Fork 648
/
router.js
116 lines (103 loc) · 2.84 KB
/
router.js
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
109
110
111
112
113
114
115
116
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use client';
// ---------------------------------------------------------
// Note: this code would usually be provided by a framework.
// ---------------------------------------------------------
import {
createContext,
startTransition,
useContext,
useState,
use,
} from 'react';
import {createFromFetch, createFromReadableStream} from 'react-server-dom-webpack/client';
const RouterContext = createContext();
const initialCache = new Map();
export function Router() {
const [cache, setCache] = useState(initialCache);
const [location, setLocation] = useState({
selectedId: null,
isEditing: false,
searchText: '',
});
const locationKey = JSON.stringify(location);
let content = cache.get(locationKey);
if (!content) {
content = createFromFetch(
fetch('/react?location=' + encodeURIComponent(locationKey))
);
cache.set(locationKey, content);
}
function refresh(response) {
startTransition(() => {
const nextCache = new Map();
if (response != null) {
const locationKey = response.headers.get('X-Location');
const nextLocation = JSON.parse(locationKey);
const nextContent = createFromReadableStream(response.body);
nextCache.set(locationKey, nextContent);
navigate(nextLocation);
}
setCache(nextCache);
})
}
function navigate(nextLocation) {
startTransition(() => {
setLocation(loc => ({
...loc,
...nextLocation
}));
});
}
return (
<RouterContext.Provider value={{location, navigate, refresh}}>
{use(content)}
</RouterContext.Provider>
);
}
export function useRouter() {
return useContext(RouterContext);
}
export function useMutation({endpoint, method}) {
const {refresh} = useRouter();
const [isSaving, setIsSaving] = useState(false);
const [didError, setDidError] = useState(false);
const [error, setError] = useState(null);
if (didError) {
// Let the nearest error boundary handle errors while saving.
throw error;
}
async function performMutation(payload, requestedLocation) {
setIsSaving(true);
try {
const response = await fetch(
`${endpoint}?location=${encodeURIComponent(
JSON.stringify(requestedLocation)
)}`,
{
method,
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json',
},
}
);
if (!response.ok) {
throw new Error(await response.text());
}
refresh(response);
} catch (e) {
setDidError(true);
setError(e);
} finally {
setIsSaving(false);
}
}
return [isSaving, performMutation];
}