npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-query-hooks

v0.0.8

Published

A simple query hook. Inspired by react-async and react-apollo.

Downloads

23

Readme

Data fetching with React Hooks, batteries included

PRs Welcome

React Query Hooks is the easiest way to manage data fetching in React apps.

It allows you to implement the following features in pretty much one line of code each:

  • Loading & error states
  • Refetching
  • Pagination
  • Polling

React Query Hooks comes with useful defaults to let you hit the ground running, yet it’s still fully customizable.

TL;DR

import { useQuery } from 'react-query-hooks';

function UserList () {
    let users = useQuery(FETCH_USERS);
  
    if (users.isLoading) return <Loading/>;
    if (users.error) return <ErrorMsg error={error} retry={users.refetch}/>;
  
    return <List
        data={users.result.data}
        onEndReached={users.loadMore}
        onRefresh={users.refetch}
    />;
}

Replace Loading, ErrorMsg & List with your own components. For this example, their source is here.

Installation

React Query Hooks has zero dependencies, and works with any app using React ^16.8.0

To install:

yarn add react-query-hooks

Or with npm:

npm install —save react-query-hooks

Usage

Let’s build a quick app that fetches data from JSONPlaceholder and renders it on a list.

First, we'll grab the useQuery hook from React Query Hooks.

import { useQuery } from 'react-query-hooks';

We'll be fetching data from jsonplaceholder, using axios;

import axios from 'axios';

const fetchUsers = () => axios("https://jsonplaceholder.typicode.com/users");

Let's make the magic happen. Inside a component, call useQuery with a function that fetches data. useQuery expects the function to return a promise.

let users = useQuery(fetchUsers);

The useQuery hook will run the passed in function, and return an object with useful properties, like isLoading and error.

if (users.loading) return <p>Loading...</p>;
if (users.error) return <p>Error!</p>

When the promise resolves, the resolved value is set to result.

<ul>
    {users.result.data.map(user => <li>{user.name}</li>)}
</ul>

And that's pretty much it. Your code should end up looking somewhat like this:

import axios from 'axios';
import { useQuery } from 'react-query-hooks';

const fetchUsers = () => axios("https://jsonplaceholder.typicode.com/users");

function Userlist () {
    let users = useQuery(fetchUsers);

    if (users.loading) return <p>Loading...</p>;
    if (users.error) return <p>Error!</p>;

    return <ul>
        {users.result.data.map(user => <li>{user.name}</li>)}
    </ul>
}

Pagination

React Query Hooks comes with pagination out of the box. So let’s keep going and add pagination to our example.

Offset based pagination involves adding two parameters to our requests:

  • limit determines how many items we want to fetch on the current request
  • offset determines how many items we want to skip on the current request (because we already loaded them)

Alright, let’s update our fetchUsers function to receive this two params:

const fetchUsers = ({ start=0, limit=3 }={}) => {
    return axios(`https://jsonplaceholder.typicode.com/users?_start=${start}&_limit=${limit}`);
};

Below our list, let’s add a button that will loadMore data onClick.

...
<button onClick={users.loadMore}>Load more!</button>
...

In a real-world app, this might be triggered as the user scrolls near the end of the list. But we’ll keep things simple for this example.

While the next page of users is loading, we want to display a loading state and hide the ‘Load more’ button.

...
{
    isLoadingMore
        ? <p>Loading more...</p>
        : <button onClick={users.loadMore}>Load more!</button>
    }
...

And now you’ve got offset pagination working. Ez. Your end code should end up looking like this:

const fetchUsers = ({ start=0, limit=3 }={}) => {
    return axios(`https://jsonplaceholder.typicode.com/users?_start=${start}&_limit=${limit}`);
};

function Userlist () {
    let users = useQuery(fetchUsers);

    if (users.loading) return <p>Loading...</p>;
    if (users.error) return <p>Error!</p>;

    return (
        <React.Fragment>
            <ul>
                {users.result.data.map(user => <li>{user.name}</li>)}
            </ul>
            {
                isLoadingMore
                    ? <p>Loading more...</p>
                    : <button onClick={users.loadMore}>Load more!</button>
            }
        </React.Fragment>
    )
}