@phalt/usequery

2.0.1 • Public • Published

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 from the fetch result. Default is res => res.json().

Usage

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 (
        <Fragment>
            <H2>My query</h2>
            <Button onClick={refetch}>Refresh</Button>
            <Button onClick={reset}>Reset state</Button>
            { loading && <h2>Loading!</h2> }
            { error && <h2>Something went wrong!</h2> }
            { data && <h3>{data}</h3> }
        </Fragment>
    );
};

POST requests

You can use the useQuery hook to do this if you want full control.

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:

import { APIQuery } from "@phalt/usequery";

const myComponent = () => {
return (<APIQuery
    ErrorState={props => <p>{props.error}</p>}
    LoadingState={() => <p>Loading...</p>}
    SuccessState={props => <p>{props.data}</p>}
    path="https://myapi.com/api/v1/foo"
/>)
}

See full example of in the "uploadin JSON data" example here.

Readme

Keywords

Package Sidebar

Install

npm i @phalt/usequery

Weekly Downloads

0

Version

2.0.1

License

GPL-3.0

Unpacked Size

41.9 kB

Total Files

5

Last publish

Collaborators

  • phalt