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 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-native-use-fetch

v3.0.1

Published

A lightweight and flexible React Native hook for managing API data fetching with pagination, error handling, refreshing, and data mutation capabilities.

Downloads

28

Readme

react-native-use-fetch

A lightweight and flexible React Native hook for managing API data fetching with pagination, error handling, refreshing, and data mutation capabilities.


Features

  • Simplifies API integration with built-in pagination and infinite scrolling.
  • Handles loading, refreshing, and error states out of the box.
  • Supports flexible data mutation methods: add, update, and delete.
  • Easily customizable with pluggable service functions and data extractors.
  • Compatible with any REST API or paginated data source.

Installation

Install the package using npm or yarn:

npm install react-native-use-fetch

or

yarn add react-native-use-fetch

Usage

The useFetch hook returns an array with three items: state, queries, and mutations. Use these to manage data fetching, query actions, and data mutations respectively.

Example

import React, { useEffect } from 'react';
import { View, Text, Button, FlatList, ActivityIndicator } from 'react-native';
import useFetch from 'react-native-use-fetch';

const fetchUsers = async ({ page }) => {
  const response = await fetch(`https://api.example.com/users?page=${page}`);
  return response.json();
};

const extractUserData = (response) => ({
  data: response.users,
  totalResults: response.total,
  currentPage: response.page,
  totalPages: response.total_pages,
});

const UsersScreen = () => {
  const [state, queries, mutations] = useFetch({
    serviceFn: fetchUsers,
    dataExtractor: extractUserData,
  });

  useEffect(() => {
    queries.fetchData();
  }, []);

  const handleAddUser = () => {
    const newUser = { id: Date.now(), name: 'New User' };
    mutations.addNewData(newUser);
  };

  const handleUpdateUser = (id) => {
    mutations.updateExistingData(id, { name: 'Updated User' });
  };

  return (
    <View style={{ flex: 1, padding: 16 }}>
      <Button title="Add User" onPress={handleAddUser} />
      {state.isFetching && <ActivityIndicator size="large" />}
      <FlatList
        data={state.data}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <View style={{ marginBottom: 10 }}>
            <Text>{item.name}</Text>
            <Button title="Update" onPress={() => handleUpdateUser(item.id)} />
            <Button
              title="Delete"
              onPress={() => mutations.deleteExistingData(item.id)}
            />
          </View>
        )}
        onEndReached={queries.fetchNextPage}
        onRefresh={queries.refetchData}
        refreshing={state.isRefreshing}
      />
      {state.error && <Text style={{ color: 'red' }}>Error: {state.error}</Text>}
    </View>
  );
};

export default UsersScreen;

Hook API

useFetch(options?: FetchProps): [FetchStateWithSetters, QueryActions, MutationActions]

This hook manages API data fetching, pagination, refreshing, error handling, and data mutations.

Parameters:

  • options (optional): Configuration object with the following properties:
    • initialData (array): Initial data to populate.
    • serviceFn (function): Async function to fetch data, receives { page: number }.
    • dataExtractor (function): Function to extract data and pagination info from the response.
    • onError (function): Callback for error handling.
    • shouldFetch (boolean): Whether to fetch data immediately on mount (default true).

Returned Values:

  • state (object): Includes both state values and setter functions.

    • State:
      • data (array)
      • error (string or null)
      • page (number)
      • hasNextPage (boolean)
      • totalResults (number or null)
      • isFetching (boolean)
      • isRefreshing (boolean)
      • isFetchingMore (boolean)
    • Setters:
      • setData(data: any[])
      • setError(error: string | null)
      • setPage(page: number)
      • setHasNextPage(boolean)
      • setTotalResults(number | null)
      • setIsFetching(boolean)
      • setIsRefreshing(boolean)
      • setIsFetchingMore(boolean)
  • queries (object):

    • fetchData(refresh?: boolean, page?: number, more?: boolean)
    • refetchData()
    • fetchNextPage()
  • mutations (object):

    • addNewData(newData)
    • updateExistingData(id, newData)
    • updateExistingDataWithKey(matchId, keyToUpdate, newValue, matchKey?)
    • deleteExistingData(id)

How it Works

  1. On mount, the hook optionally fetches data from an API using a user-provided serviceFn.
  2. The dataExtractor processes and structures the API response, including pagination.
  3. Fetch state is split between querying (fetchData, refetchData, fetchNextPage) and mutation (addNewData, updateExistingData, etc.) actions.
  4. Built-in setters (e.g., setData, setError, etc.) allow manual control over hook state.
  5. Mutation methods offer convenient, immutable updates to the data array.
  6. Pagination and infinite scroll are supported automatically using hasNextPage and page tracking.

Contributing

Contributions are welcome! If you have improvements, bug fixes, or ideas, feel free to fork the repo and submit a pull request. Be sure to include tests and follow the coding style used throughout the project. Discuss features or bugs via GitHub Issues.


Issues and Support

Need help or found a bug? Open an issue on the GitHub Issues page. We're happy to help!


License

Licensed under the MIT License. See the LICENSE file for full details.


Author

Created by Moses Esan.