0.0.7 • Published 1 year ago
@zachtu/use-fetch v0.0.7
@zachtu/use-fetch
A useful React fetching hook
npm i @zachtu/use-fetch
Usage
Make a GET request
const { data: todos, loading, error } = useFetch("/todos")
return (
<>
{loading && <div>Loading...</div>}
{error && <div>Error!</div>}
{todos.map((todo) => (
<div key={todo.id}>{todo.title}</div>
))}
</>
)
Make a POST, PUT or DELETE request
const {
data: todos,
loading,
error,
set, // Used to update the `data` state
post, // Available method functions are `post`, `put` and `del`
} = useFetch("/todos")
const addTodo = async () => {
const { data: newTodo, error } = await post("/todos", { title: "New todo" }) // The method functions require a URL and a body
if (!error) {
set([...todos, newTodo])
} else {
console.log(error.status, error.statusText) // `status` and `statusText` come from the response object
}
}
Add options to the fetches
const {
data: todos,
loading,
error,
} = useFetch("/todos", {
// The available options are the same as the global `fetch` method, but with some extras:
depends: [authToken], // This won't fetch until all of these are truthy
formatter: (response) => response.text(), // If this isn't provided, it will format the response as JSON
})
const addTodo = async () => {
const { data, error } = await post(
"/todos",
{ title: "New todo" },
{
formatter: (response) => response.text(),
// Only the `useFetch` hook accepts the `depends` array
}
)
}
Refetch the GET request
const { data: todos, loading, error, refetch } = useFetch("/todos")
const refreshTodos = () => {
await refetch() // This will use the options from the `useFetch` hook, but it will ignore the `depends` array
}