Whenever possible, we try to follow standard usage of the
fetch()
API as closely as possible. There are a few differences between using fetch()
and this
library, though, which are explained here.
The second argument to fetch()
is an optional object called init
. With
<Fetch/>
, the object has been spread out as props. This change was made
for aesthetic reasons: I find it ugly to pass objects as props.
fetch('/posts/2', {
method: 'PATCH',
credentials: 'include',
body: JSON.stringify({ title: 'New post' })
});
<Fetch
url="/posts/2"
method="PATCH"
credentials="include"
body={JSON.stringify({ title: 'New post' })}
/>
When using fetch
, you must manually read the body. This
library reads it automatically for you. This is because the body
is a ReadableStream, and can only be read a single time. It was
a requirement that React Request read it for you to support
deduplication of requests.
fetch('/posts/2', {
method: 'PATCH',
credentials: 'include',
body: JSON.stringify({ title: 'New post' })
})
.then(res => res.body.json())
.then(data => {
console.log('Got my JSON', data);
});
<Fetch
url="/posts/2"
method="PATCH"
credentials="include"
body={JSON.stringify({ title: 'New post' })}>
{({ data }) => {
console.log('Got my JSON', data);
return null;
}}
</Fetch>
For now, you may only pass strings as the request body. This is due to the fact that we need to build a request key for request deduplication and response caching.
In the future, we plan to add support for additional request body types.
When aborting fetch()
, you will typically do the following:
- Create an AbortController object
- Pass the AbortSignal object into
fetch
This system does not work with <Fetch/>
, because it would be tedious
for you to create a new AbortController anytime the component was going
to make a new request.
It is on our roadmap to provide a great story around aborting requests. For more, see the guide on aborting requests.