Skip to content

Commit df97043

Browse files
authored
docs(guides/deferred): add FAQ about using Response objects with defer (#10000)
1 parent 171b195 commit df97043

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

contributors.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@
105105
- koojaa
106106
- KostiantynPopovych
107107
- KutnerUri
108+
- landisdesign
108109
- latin-1
109110
- lequangdongg
110111
- liuhanqu

docs/guides/deferred.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,43 @@ When you decide you'd like to try the trade-offs of `defer`, we don't want you t
207207
208208
So just keep this in mind: **Deferred is 100% only about the initial load of a route and its params.**
209209
210+
### Why don't Response objects returned by the loader work anymore?
211+
212+
When you use `defer`, you're telling React Router to load the page immediately, without the deferred data. The page is already loaded before the `Response` object is returned so responses are not automatically processed in the same way as if you had done `return fetch(url)`.
213+
214+
Therefore, you will need to handle your own `Response` processing and resolve your deferred Promise with data, not a `Response` instance.
215+
216+
```jsx
217+
async function loader({ request, params }) {
218+
return defer({
219+
// Broken! Resolves with a Response
220+
// broken: fetch(url),
221+
222+
// Fixed! Resolves with the response data
223+
data: fetch(url).then((res) => res.json()),
224+
});
225+
}
226+
```
227+
228+
Or consider the scenario where our deferred data could return a redirect `Response`. You can detect the redirect and send the status code and location back as data, and then you could perform a client-side redirect in your component via `useEffect` and `useNavigate`.
229+
230+
```jsx
231+
async function loader({ request, params }) {
232+
let data = fetch(url).then((res) => {
233+
if (res.status == 301) {
234+
return {
235+
isRedirect: true,
236+
status: res.status,
237+
location: res.headers.get("Location"),
238+
};
239+
}
240+
return res.json();
241+
});
242+
243+
return defer({ data });
244+
}
245+
```
246+
210247
[link]: ../components/link
211248
[usefetcher]: ../hooks/use-fetcher
212249
[defer response]: ../utils/defer

0 commit comments

Comments
 (0)