React hook for making isomorphic http requests
[![use-http logo][3]][5]
url and optionsuseFetchIf the last argument of useFetch is not a dependency array [], then it will not fire until you call one of the http methods like get, post, etc.
…useFetchThis fetch is run onMount/componentDidMount. The last argument [] means it will run onMount. If you pass it a variable like [someVariable], it will run onMount and again whenever someVariable changes values (aka onUpdate). If no method is specified, GET is the default.
import useFetch from 'use-http'
function Todos() {
const options = {} // these options accept all native `fetch` options
// the last argument below [] means it will fire onMount (GET by default)
const { loading, error, data = [] } = useFetch('https://example.com/todos', options, [])
return (
<>
{error && 'Error!'}
{loading && 'Loading...'}
{data.map(todo => (
))}
</>
)
}Can put suspense in 2 places. Either useFetch (A) or Provider (B).
import useFetch, { Provider } from 'use-http'
function Todos() {
const { data: todos = [] } = useFetch('/todos', {
suspense: true // A. can put `suspense: true` here
}, []) // onMount
return todos.map(todo =>
)
}
function App() {
const options = {
suspense: true // B. can put `suspense: true` here too
}
return (
<Provider url='https://example.com' options={options}>
<Suspense fallback='Loading...'>
<Todos />
</Suspense>
</Provider>
)
}Can put suspense in 2 places. Either useFetch (A) or Provider (B). Suspense mode via managed state is very experimental.
…ProviderThe onNewData will take the current data, and the newly fetched data, and allow you to merge the two however you choose. In the example below, we are appending the new todos to the end of the current todos.
…useFetch⚠️ Do not destructure the response object! Details in this video. Technically you can do it, but if you need to access the response.ok from, for example, within a component's onClick handler, it will be a stale value for ok where it will be correct for response.ok. ️️⚠️
…useFetchvar request = useFetch('https://example.com')
request.post('/todos', {
no: 'way'
})useFetchconst { get, abort, loading, data: repos } = useFetch('https://api.github.com/search/repositories?q=')
// the line below is not isomorphic, but for simplicity we're using the browsers `encodeURI`
const searchGithubRepos = e => get(encodeURI(e.target.value))
<>
<input onChange={searchGithubRepos} />
<button onClick={abort}>Abort</button>
{loading ? 'Loading...' : repos.data.items.map(repo => (
))}
</>useFetch
const QUERY = `
query Todos($userID string!) {
todos(userID: $userID) {
id
title
}
}
`
function App() {
const request = useFetch('http://example.com')
const getTodosForUser = id => request.query(QUERY, { userID: id })
return (
<>
<button onClick={() => getTodosForUser('theUsersID')}>Get User's Todos</button>
{request.loading ? 'Loading...' : <pre>{request.data}</pre>}
</>
)
}useFetchThe Provider allows us to set a default url, options (such as headers) and so on.
const MUTATION = `
mutation CreateTodo($todoTitle string) {
todo(title: $todoTitle) {
id
title
}
}
`
function App() {
const [todoTitle, setTodoTitle] = useState('')
const request = useFetch('http://example.com')
const createtodo = () => request.mutate(MUTATION, { todoTitle })
return (
<>
<input onChange={e => setTodoTitle(e.target.value)} />
<button onClick={createTodo}>Create Todo</button>
{request.loading ? 'Loading...' : <pre>{request.data}</pre>}
</>
)
}Provider using the GraphQL useMutation and useQuery……These props are defaults used in every request inside the <Provider />. They can be overwritten individually
import { Provider } from 'use-http'
import QueryComponent from './QueryComponent'
import MutationComponent from './MutationComponent'
function App() {
const options = {
headers: {
Authorization: 'Bearer YOUR_TOKEN_HERE'
}
}
return (
<Provider url='http://example.com' options={options}>
<QueryComponent />
<MutationComponent />
<Provider/>
)
}
This example shows how we can do authentication in the request interceptor and how we can camelCase the results in the response interceptor
…This example shows how we can upload a file using useFetch.
import useFetch from 'use-http'
const FileUploader = () => {
const [file, setFile] = useState()
const { post } = useFetch('https://example.com/upload')
const uploadFile = async () => {
const data = new FormData()
data.append('file', file)
if (file instanceof FormData) await post(data)
}
return (
)
}This example shows how we can get .json(), .text(), .formData(), .blob(), .arrayBuffer(), and all the other http response methods. By default, useFetch 1st tries to call response.json() under the hood, if that fails it's backup is response.text(). If that fails, then you need a different response type which is where this comes in.
import useFetch from 'use-http'
const App = () => {
const [name, setName] = useState('')
const { get, loading, error, response } = useFetch('http://example.com')
const handleClick = async () => {
await get('/users/1?name=true') // will return just the user's name
const text = await response.text()
setName(text)
}
return (
<>
<button onClick={handleClick}>Load Data</button>
{error && error.messge}
{loading && "Loading..."}
{name &&
}
</>
)
}<
No open issues yet, or sync has not completed.