https://github.com/phalt/usequery
A React hook for making REST API calls
https://github.com/phalt/usequery
Last synced: 5 months ago
JSON representation
A React hook for making REST API calls
- Host: GitHub
- URL: https://github.com/phalt/usequery
- Owner: phalt
- License: gpl-3.0
- Created: 2020-02-13T03:11:59.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2023-01-05T07:15:10.000Z (over 3 years ago)
- Last Synced: 2025-04-06T23:42:36.451Z (about 1 year ago)
- Language: JavaScript
- Homepage:
- Size: 864 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 11
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# useQuery
A simple React hook and component for handling REST API calls.
Provides loading state, success state, and error states.
## useQuery(url, options, deserialize)
Requires a `url` parameter.
If `options` not supplied, defaults to an empty object. Put your `fetchOptions` here.
Argument `deserialize` is a callback that takes [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) from the fetch result. Default is `res => res.json()`.
### Usage
```js
import React, { Fragment } from "react";
import { useQuery } from '@phalt/usequery';
export const myComponent = () => {
const [{ data, loading, error }, { refetch, reset }] = useQuery({
url: "https://pokeapi.co/api",
{ headers: { accept: "application/json" }}
});
return (
My query
Refresh
Reset state
{ loading && Loading!
}
{ error && Something went wrong!
}
{ data && {data}
}
);
};
```
## POST requests
You can use the `useQuery` hook to do this if you want full control.
```js
import { useQuery } from '@phalt/usequery';
const httpOptions = {
headers: { "Content-Type": "application/json" },
method: "POST",
body: JSON.stringify(myData)
};
const [{ data, loading, error }, { refetch, reset }] = useQuery({
url: "https://example.com/resource",
httOptions
});
```
## APIQuery component
For convenience we ship an APIQuery component:
```js
import { APIQuery } from "@phalt/usequery";
const myComponent = () => {
return (
{props.error}
}
LoadingState={() => Loading...
}
SuccessState={props => {props.data}
}
path="https://myapi.com/api/v1/foo"
/>)
}
```
See full example of in the "uploadin JSON data" example [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).