Gathering detailed insights and metrics for use-invariant
Gathering detailed insights and metrics for use-invariant
Gathering detailed insights and metrics for use-invariant
Gathering detailed insights and metrics for use-invariant
npm install use-invariant
Typescript
Module System
Removal of "path" and "url" fields
Updated on Apr 23, 2020
Scalable Interceptor Arguments, responseType option
Updated on Apr 17, 2020
Version 1.0
Updated on Apr 14, 2020
Pagination + Moving to dependency array for onMount + onUpdate
Updated on Nov 19, 2019
Support for a Provider, useMutation, and useQuery
Updated on Jun 20, 2019
Abort Functionality
Updated on Apr 28, 2019
TypeScript (99.13%)
JavaScript (0.87%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
2,310 Stars
714 Commits
115 Forks
17 Watchers
18 Branches
36 Contributors
Updated on Jul 09, 2025
Latest Version
0.1.70
Package Id
use-invariant@0.1.70
Unpacked Size
60.11 kB
Size
14.82 kB
File Count
44
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
🐶 React hook for making isomorphic http requests
Need to fetch some data? Try this one out. It's an isomorphic fetch hook. That means it works with SSR (server side rendering).
A note on the documentation below. Many of these examples could have performance improvements using useMemo
and useCallback
, but for the sake of the beginner/ease of reading, they are left out.
url
and options
1yarn add use-http or npm i -S use-http
1import useFetch from 'use-http' 2 3function Todos() { 4 const options = { // accepts all `fetch` options 5 onMount: true // will fire on componentDidMount 6 } 7 8 const todos = useFetch('https://example.com/todos', options) 9 10 function addTodo() { 11 todos.post({ 12 title: 'no way', 13 }) 14 } 15 16 if (todos.error) return 'Error!' 17 if (todos.loading) return 'Loading...' 18 19 return ( 20 <> 21 <button onClick={addTodo}>Add Todo</button> 22 {todos.data.map(todo => ( 23 <div key={todo.id}>{todo.title}</div> 24 )} 25 </> 26 ) 27}
1var [data, loading, error, request] = useFetch('https://example.com') 2 3// want to use object destructuring? You can do that too 4var { data, loading, error, request } = useFetch('https://example.com')
1const request = useFetch({ 2 baseUrl: 'https://example.com' 3}) 4 5request.post('/todos', { 6 no: 'way' 7})
1import { useGet, usePost, usePatch, usePut, useDelete } from 'use-http' 2 3const [data, loading, error, patch] = usePatch({ 4 url: 'https://example.com', 5 headers: { 6 'Accept': 'application/json; charset=UTF-8' 7 } 8}) 9 10patch({ 11 yes: 'way', 12})
1const githubRepos = useFetch({ 2 baseUrl: `https://api.github.com/search/repositories?q=` 3}) 4 5// the line below is not isomorphic, but for simplicity we're using the browsers `encodeURI` 6const searchGithubRepos = e => githubRepos.get(encodeURI(e.target.value)) 7 8<> 9 <input onChange={searchGithubRepos} /> 10 <button onClick={githubRepos.abort}>Abort</button> 11 {githubRepos.loading ? 'Loading...' : githubRepos.data.items.map(repo => ( 12 <div key={repo.id}>{repo.name}</div> 13 ))} 14</>
1 2const QUERY = ` 3 query Todos($userID string!) { 4 todos(userID: $userID) { 5 id 6 title 7 } 8 } 9` 10 11function App() { 12 const request = useFetch('http://example.com') 13 14 const getTodosForUser = id => request.query(QUERY, { userID: id }) 15 16 return ( 17 <> 18 <button onClick={() => getTodosForUser('theUsersID')}>Get User's Todos</button> 19 {request.loading ? 'Loading...' : <pre>{request.data}</pre>} 20 </> 21 ) 22}
1 2const MUTATION = ` 3 mutation CreateTodo($todoTitle string) { 4 todo(title: $todoTitle) { 5 id 6 title 7 } 8 } 9` 10 11function App() { 12 const [todoTitle, setTodoTitle] = useState('') 13 const request = useFetch('http://example.com') 14 15 const createtodo = () => request.mutate(MUTATION, { todoTitle }) 16 17 return ( 18 <> 19 <input onChange={e => setTodoTitle(e.target.value)} /> 20 <button onClick={createTodo}>Create Todo</button> 21 {request.loading ? 'Loading...' : <pre>{request.data}</pre>} 22 </> 23 ) 24}
Provider
using the GraphQL useMutation
and useQuery
The Provider
allows us to set a default url
, options
(such as headers) and so on.
1import { Provider, useQuery, useMutation } from 'use-http' 2 3function QueryComponent() { 4 const request = useQuery` 5 query Todos($userID string!) { 6 todos(userID: $userID) { 7 id 8 title 9 } 10 } 11 ` 12 13 const getTodosForUser = id => request.query({ userID: id }) 14 15 return ( 16 <> 17 <button onClick={() => getTodosForUser('theUsersID')}>Get User's Todos</button> 18 {request.loading ? 'Loading...' : <pre>{request.data}</pre>} 19 </> 20 ) 21}
1function MutationComponent() { 2 const [todoTitle, setTodoTitle] = useState('') 3 4 const [data, loading, error, mutate] = useMutation` 5 mutation CreateTodo($todoTitle string) { 6 todo(title: $todoTitle) { 7 id 8 title 9 } 10 } 11 ` 12 13 const createTodo = () => mutate({ todoTitle }) 14 15 return ( 16 <> 17 <input onChange={e => setTodoTitle(e.target.value)} /> 18 <button onClick={createTodo}>Create Todo</button> 19 {loading ? 'Loading...' : <pre>{data}</pre>} 20 </> 21 ) 22}
These props are defaults used in every request inside the <Provider />
. They can be overwritten individually
1function App() { 2 3 const options = { 4 headers: { 5 Authorization: 'Bearer:asdfasdfasdfasdfasdafd' 6 } 7 } 8 9 return ( 10 <Provider url='http://example.com' options={options}> 11 <QueryComponent /> 12 <MutationComponent /> 13 <Provider/> 14 ) 15} 16
1import React, { Suspense, unstable_ConcurrentMode as ConcurrentMode, useEffect } from 'react' 2 3function WithSuspense() { 4 const suspense = useFetch('https://example.com') 5 6 useEffect(() => { 7 suspense.read() 8 }, []) 9 10 if (!suspense.data) return null 11 12 return <pre>{suspense.data}</pre> 13} 14 15function App() ( 16 <ConcurrentMode> 17 <Suspense fallback="Loading..."> 18 <WithSuspense /> 19 </Suspense> 20 </ConcurrentMode> 21)
Option | Description |
---|---|
useFetch | The base hook |
useGet | Defaults to a GET request |
usePost | Defaults to a POST request |
usePut | Defaults to a PUT request |
usePatch | Defaults to a PATCH request |
useDelete | Defaults to a DELETE request |
useQuery | For making a GraphQL query |
useMutation | For making a GraphQL mutation |
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 |
baseUrl | Allows you to set a base path so relative paths can be used for each request :) | empty string |
1const {
2 data,
3 loading,
4 error,
5 request,
6 get,
7 post,
8 patch,
9 put,
10 delete // don't destructure `delete` though, it's a keyword
11 del, // <- that's why we have this (del). or use `request.delete`
12 abort,
13 query, // GraphQL
14 mutate, // GraphQL
15} = useFetch({
16 // accepts all `fetch` options such as headers, method, etc.
17 url: 'https://example.com',
18 baseUrl: 'https://example.com',
19 onMount: true
20})
or
1const [data, loading, error, request] = useFetch({
2 // accepts all `fetch` options such as headers, method, etc.
3 url: 'https://example.com',
4 baseUrl: 'https://example.com',
5 onMount: true
6})
7
8const {
9 get,
10 post,
11 patch,
12 put,
13 delete // don't destructure `delete` though, it's a keyword
14 del, // <- that's why we have this (del). or use `request.delete`
15 abort,
16 query, // GraphQL
17 mutate, // GraphQL
18} = request
use-http is heavily inspired by the popular http client axios
If you have feature requests, let's talk about them in this issue!
window.location.origin
client
) but better 😉useQuery
, useMutation
loading
statetimeout
debounce
retries: 3
which would specify the amount of times it should retry before erroring outuseQuery('my query')
without specifiying a URL in the Provider, throw erroroptions
(as 2nd param) to all hooks is an object, if not invariant
/throw error1 const user = useFetch() 2 3 user 4 .headers({ 5 auth: jwt 6 }) 7 .get() 8
1const App = () => { 2 const [todoTitle, setTodoTitle] = useState('') 3 // if there's no <Provider /> used, useMutation works this way 4 const mutation = useMutation('http://example.com', ` 5 mutation CreateTodo($todoTitle string) { 6 todo(title: $todoTitle) { 7 id 8 title 9 } 10 } 11 `) 12 13 // ideally, I think it should be mutation.write({ todoTitle }) since mutation ~= POST 14 const createTodo = () => mutation.read({ todoTitle }) 15 16 if (!request.data) return null 17 18 return ( 19 <> 20 <input onChange={e => setTodoTitle(e.target.value)} /> 21 <button onClick={createTodo}>Create Todo</button> 22 <pre>{mutation.data}</pre> 23 </> 24 ) 25}
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 12/30 approved changesets -- score normalized to 4
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
34 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More