react-refetch-hooks
v0.0.25
Published
![GitHub](https://img.shields.io/github/license/Luncher/react-fetch?style=for-the-badge) ![npm](https://img.shields.io/npm/v/react-refetch-hooks?style=for-the-badge) ![Travis (.com)](https://img.shields.io/travis/com/Luncher/react-fetch?style=for-the-badg
Downloads
41
Readme
react-fetch
Quick Start
npm install react-refetch-hooks
Query
import { useQuery } from 'react-refetch-hooks'
function App() {
const { data, loading, error, update } = useQuery(
() => fetch('https://jsonplaceholder.typicode.com/todos/1')
)
if (loading) return <p>Loading...</p>
if (error) return <p>Error :(</p>
return (
<div>
<p>title: {data.title}</p>
<p>completed: {data.completed}</p>
<button onClick={() => update()}>refresh</button>
</div>
)
}
Imperative Query
import { useQuery } from 'react-refetch-hooks'
function App() {
const { data, loading, error, fetch } = useQuery(
(page: number) => 'https://jsonplaceholder.typicode.com/todos/1',
{ imperative: true }
)
if (loading) return <p>Loading...</p>
if (error) return <p>Error :(</p>
return (
<div>
<p>title: {data.title}</p>
<p>completed: {data.completed}</p>
<button onClick={() => fetch(1)}>refresh</button>
</div>
)
}
Mutation
import { useMutation } from 'react-refetch-hooks'
const url = 'https://jsonplaceholder.typicode.com/todos'
const fetcher = (form) => fetch(url, {
method: 'POST',
body: form
}).then(res => res.json())
function TodoForm() {
const { mutating, error, trigger } = useMutation(fetcher)
if (error) return <p>Error :(</p>
const handleSubmit = (event) => {
event.preventDefault()
const formData = new FormData(event.target)
try {
await trigger(formData)
} catch (err) {
console.log(err)
}
}
return (
<form onSubmit={handleSubmit}>
<label>
Title: <input name="title" type="text"></input>
</label>
<input type="submit" disabled={mutating}>Submit</input>
</form>
)
}
Q&A
declarative vs imperative
When you choose whether to use declarative or imperative, the main question you need to answer is what kind of logic it is from the user’s perspective. If this logic is caused by a particular interaction, and the query result just using once and not use for rendering ui, then imperative, otherwise declarative.
inspired by you-might-not-need-an-effect
imperative mode withouts any revalidate options.
Features
Basic
- [x] Fetch OnMount.
- [x] Dependent Fetching of data that depends on other.
- [x] Automatic Refetching.
- [x] Window focus
- [x] Network reconnect
- [x] Interval
- [x] Request deduplication.
- [x] Debounced Request
- [x] Prevents potential race conditions
- [x] Separate Mutation and Query
- [x] Triggering the mutation manually
Advanced
- [ ] fallbackData vs placeholderData vs keepPreviousData
- [ ] Global configuration available or per hook call.
- [ ] Built-in cache
- [ ] Infinite: pagination and infinite scroll loading.
- [ ] Error handling, Error Retry
- [ ] Supports optimistic UI functionalities
- [ ] Suspense