Fetching on-demand vs only in "componentDidMount"
Changing the original behavior from only fetching on mount to whenever you want.
Previous behavior:
import useFetch from 'use-http'
function App() {
// add whatever other options you would add to `fetch` such as headers
const options = {
method: 'POST',
body: {}, // whatever data you want to send
}
var [data, loading, error] = useFetch('https://example.com', options)
// want to use object destructuring? You can do that too
var { data, loading, error } = useFetch('https://example.com', options)
if (error) return 'Error!'
if (loading) return 'Loading!'
return (
<code>
<pre>{data}</pre>
</code>
)
}
this would only work when the component first rendered. Now we can do
import useFetch from 'use-http'
function App() {
// add whatever other options you would add to `fetch` such as headers
const options = {}
var [data, loading, error, request] = useFetch('https://example.com', options)
// want to use object destructuring? You can do that too
var { data, loading, error, request, get, post, patch, put, del } = useFetch('https://example.com')
const postData = () => {
post({
no: 'way',
})
// OR
request.post({
no: 'way',
})
}
if (error) return 'Error!'
if (loading) return 'Loading!'
return (
<>
<button onClick={postData}>Post Some Data</button>
<code>
<pre>{data}</pre>
</code>
</>
)
}
There's also support for
var [data, loading, error, request] = useFetch({
onMount: true, // will fire on componentDidMount
baseUrl: 'https://example.com'
})
const handleClick = () => {
request.post('/todos', {
id: 'someID',
text: 'this is what my todo is'
})
}
And don't forget
var { data, loading, error, patch } = usePatch({
url: 'https://example.com',
headers: {
'Content-type': 'application/json; charset=UTF-8'
}
})