1.0.0 • Published 5 months ago

react-native-use-fetch v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

react-native-use-fetch

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


Features

  • Fetch and manage paginated data effortlessly.
  • Provides error handling and loading state management.
  • Supports manual refreshing and infinite scrolling.
  • Fully customizable with service functions and data extraction utilities.
  • Designed to work seamlessly with any API structure.

Installation

Install the package using npm or yarn:

npm install react-native-use-fetch

or

yarn add react-native-use-fetch

Usage

Basic 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, actions] = useFetch({
    serviceFn: fetchUsers,
    dataExtractor: extractUserData,
  });

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

  return (
    <View style={{ flex: 1, padding: 16 }}>
      {state.isFetching && <ActivityIndicator size="large" />}
      <FlatList
        data={state.data}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => <Text>{item.name}</Text>}
        onEndReached={actions.fetchNextPage}
        onRefresh={actions.refetchData}
        refreshing={state.isRefreshing}
      />
      {state.error && <Text style={{ color: 'red' }}>Error: {state.error}</Text>}
    </View>
  );
};

export default UsersScreen;

Hook API

useFetch(options?: FetchProps)

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

Parameters:

  • initialData (optional, array): Default dataset before fetching.
  • serviceFn (optional, function): API function to fetch data (async ({ page }) => {}).
  • dataExtractor (optional, function): Function to extract data, page count, and metadata from the API response.
  • onError (optional, function): Callback for handling errors.
  • shouldFetch (optional, boolean): Determines if fetching should start automatically. Defaults to true.

Returned Values:

  • state (object):

    • data (array): Fetched data.
    • error (string or null): Error message if an error occurs.
    • page (number): Current page number.
    • hasNextPage (boolean): Indicates if more pages are available.
    • totalResults (number or null): Total number of results (if available).
    • isFetching (boolean): Indicates if initial fetch is in progress.
    • isRefreshing (boolean): Indicates if data is being refreshed.
    • isFetchingMore (boolean): Indicates if additional pages are being fetched.
  • actions (object):

    • fetchData(refresh?: boolean, page?: number, more?: boolean): Fetches new data.
    • refetchData(): Refreshes the current data set.
    • fetchNextPage(): Loads the next page of data.

How it Works

  1. The hook uses a provided serviceFn to fetch data from an API.
  2. The dataExtractor function processes the response and extracts relevant fields.
  3. State management includes error handling, pagination control, and loading indicators.
  4. Supports infinite scrolling and manual refreshing.

Contributing

We welcome contributions! Feel free to submit issues or pull requests on the GitHub repository.


Issues and Support

If you encounter any issues or need help, please create an issue on the GitHub repository.


License

MIT License. See the LICENSE file for more information.


Author

Created by Moses Esan.

1.0.0

5 months ago