useFetch
Features
- SSR (server side rendering) support
- TypeScript support
- 1 dependency (use-ssr)
- GraphQL support (queries + mutations)
- Provider to set default
url
and options
Usage
⚠️ Examples click me
Basic Usage (managed state) useFetch
import useFetch from 'use-http'
function Todos() {
const [todos, setTodos] = useState([])
const [request, response] = useFetch('https://example.com')
const mounted = useRef(false)
useEffect(() => {
if (!mounted.current) {
initializeTodos()
mounted.current= true
}
})
async function initializeTodos() {
const initialTodos = await request.get('/todos')
if (response.ok) setTodos(initialTodos)
}
async function addTodo() {
const newTodo = await request.post('/todos', {
title: 'no way',
})
if (response.ok) setTodos([...todos, newTodo])
}
return (
<>
<button onClick={ addTodo }>Add Todo</button>
{request.error && 'Error!'}
{request.loading && 'Loading...'}
{todos.length > 0 && todos.map(todo => (
<div key={todo.id}>{todo.title}</div>
)}
</>
)
}
Basic Usage (no managed state) useFetch
import useFetch from 'use-http'
function Todos() {
const options = {
onMount: true,
data: []
}
const { loading, error, data, post } = useFetch('https://example.com/todos', options)
function addTodo() {
post({
title: 'no way'
})
}
return (
<>
<button onClick={addTodo}>Add Todo</button>
{error && 'Error!'}
{loading && 'Loading...'}
{!loading && data.map(todo => (
<div key={todo.id}>{todo.title}</div>
)}
</>
)
}
Destructured useFetch
var [request, response, loading, error] = useFetch('https://example.com')
var {
request,
response,
loading,
error,
data,
get,
post,
put,
patch,
delete
del,
mutate,
query,
abort
} = useFetch('https://example.com')
var {
loading,
error,
data,
get,
post,
put,
patch,
delete
del,
mutate,
query,
abort
} = request
var {
data,
ok,
headers,
...restOfHttpResponse
} = response
Relative routes useFetch
⚠️ baseUrl
is no longer supported, it is now only url
var request = useFetch({ url: 'https://example.com' })
var request = useFetch('https://example.com')
request.post('/todos', {
no: 'way'
})
Abort useFetch
const githubRepos = useFetch({
url: `https://api.github.com/search/repositories?q=`
})
const searchGithubRepos = e => githubRepos.get(encodeURI(e.target.value))
<>
<input onChange={searchGithubRepos} />
<button onClick={githubRepos.abort}>Abort</button>
{githubRepos.loading ? 'Loading...' : githubRepos.data.items.map(repo => (
<div key={repo.id}>{repo.name}</div>
))}
</>
GraphQL Query 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>}
</>
)
}
GraphQL Mutation useFetch
The 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
Query for todos
import { useQuery } from 'use-http'
export default function QueryComponent() {
const request = useQuery`
query Todos($userID string!) {
todos(userID: $userID) {
id
title
}
}
`
const getTodosForUser = id => request.query({ userID: id })
return (
<>
<button onClick={() => getTodosForUser('theUsersID')}>Get User's Todos</button>
{request.loading ? 'Loading...' : <pre>{request.data}</pre>}
</>
)
}
Add a new todo
import { useMutation } from 'use-http'
export default function MutationComponent() {
const [todoTitle, setTodoTitle] = useState('')
const [data, loading, error, mutate] = useMutation`
mutation CreateTodo($todoTitle string) {
todo(title: $todoTitle) {
id
title
}
}
`
const createTodo = () => mutate({ todoTitle })
return (
<>
<input onChange={e => setTodoTitle(e.target.value)} />
<button onClick={createTodo}>Create Todo</button>
{loading ? 'Loading...' : <pre>{data}</pre>}
</>
)
}
Adding the Provider
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/>
)
}
Overview
Hooks
Hook | Description |
---|
useFetch | The base hook |
useQuery | For making a GraphQL query |
useMutation | For making a GraphQL mutation |
Options
This is exactly what you would pass to the normal js fetch
, with a little extra.
Option | Description | Default |
---|
onMount | Once the component mounts, the http request will run immediately | false |
url | Allows you to set a base path so relative paths can be used for each request :) | empty string |
data | Allows you to set a default value for data | undefined |
loading | Allows you to set default value for loading | false unless onMount === true |
useFetch({
url: 'https://example.com',
onMount: true,
data: [],
loading: false,
})
Feature Requests/Ideas
If you have feature requests, let's talk about them in this issue!
Todos
const App = () => {
const { get } = useFetch('https://example.com')
const [accessToken, setAccessToken] = useLocalStorage('access-token')
const [refreshToken, setRefreshToken] = useLocalStorage('refresh-token')
const { history } = useReactRouter()
const options = {
interceptors: {
async request(opts) {
let headers = {}
if (!refreshToken || isExpired(refreshToken)) {
return history.push('/login')
}
if (!accessToken || isExpired(accessToken)) {
const access = await get(`/access-token?refreshToken=${refreshToken}`)
setAccessToken(access)
headers = {
Authorization: `Bearer ${access}`,
}
}
const finalOptions = {
...opts,
headers: {
...opts.headers,
...headers,
},
}
return finalOptions
},
},
headers: {
Authorization: `Bearer ${accessToken}`
}
}
return (
<Provider url='https://example.com' options={options}>
<App />
</Provider>
)
}
const user = useFetch()
user
.headers({
auth: jwt
})
.get()
<Provider responseKeys={{ case: 'camel' }}><App /></Provider>
const request = useFetch('url', {
onUpdate: [props.id]
})
const request = useFetch('https://url.com', globalOptions => {
delete globalOptions.headers.Authorization
return globalOptions
})
The Goal With Suspense (not implemented yet)
import React, { Suspense, unstable_ConcurrentMode as ConcurrentMode, useEffect } from 'react'
function WithSuspense() {
const suspense = useFetch('https://example.com')
useEffect(() => {
suspense.read()
}, [])
if (!suspense.data) return null
return <pre>{suspense.data}</pre>
}
function App() (
<ConcurrentMode>
<Suspense fallback="Loading...">
<WithSuspense />
</Suspense>
</ConcurrentMode>
)
GraphQL with Suspense (not implemented yet)
const App = () => {
const [todoTitle, setTodoTitle] = useState('')
const mutation = useMutation('http://example.com', `
mutation CreateTodo($todoTitle string) {
todo(title: $todoTitle) {
id
title
}
}
`)
const createTodo = () => mutation.read({ todoTitle })
if (!request.data) return null
return (
<>
<input onChange={e => setTodoTitle(e.target.value)} />
<button onClick={createTodo}>Create Todo</button>
<pre>{mutation.data}</pre>
</>
)
}