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

useipa

v0.4.0

Published

A react hook for api fetching

Downloads

19

Readme

npm version   Build status   MIT license

useipa Package

A Powerful and Lightweight React Hook for Managing API Calls and Forms

The useipa package provides custom hooks for API interaction in React applications using Axios. It includes hooks for fetching data, mutating data, and submitting forms with integrated state management for loading, success, and error states.

Installation

To install the package, run:

npm install useipa
# or
yarn add useipa

Usage

ApiClientProvider

Setting Up ApiClientProvider First, import the necessary components and set up your ApiClientProvider with the desired configuration.Within any child component, you can use the useApi hook to access the configured Axios instance.

import { ApiClientProvider } from 'useipa';

const apiClientConfig = {
  baseURL: 'https://api.example.com',
  headers: {
    Authorization: 'Bearer YOUR_ACCESS_TOKEN',
  },
};

const App = () => {
  return (
    <ApiClientProvider client={apiClientConfig}>
      <YourComponent />
    </ApiClientProvider>
  );
};

export default App;

useApi The Core Hook

The useApi hook provides methods for fetching and mutating data from an API. Fetches data, mutates resources, and submits forms using a unified API.

Provides state management for data, error, fetching, and success.

Offers the following methods:

Example: Fetching Data

import { useEffect } from 'react'
import { useApi } from 'useipa'

const FetchComponent = () => {
  const { data, fetching, error, fetchData } = useApi()

  useEffect(() => {
    fetchData('/api/data')
  }, [fetchData])

  if (fetching) return <p>Loading...</p>
  if (error) return <p>Error: {error.message}</p>
  return (
    <div>
      <h1>Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  )
}

export default FetchComponent

Example: Mutating Data

import { useState } from 'react'
import { useApi } from 'useipa'

const MutateComponent = () => {
  const [inputValue, setInputValue] = useState('')
  const { data, success, error, mutate } = useApi()

  const handleSubmit = () => {
    mutate('/api/data', { value: inputValue })
  }

  return (
    <div>
      <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
      <button onClick={handleSubmit}>Submit</button>
      {success && <p>Success!</p>}
      {error && <p>Error: {error.message}</p>}
      {data && (
        <div>
          <h1>Response</h1>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      )}
    </div>
  )
}

export default MutateComponent

The ApiClientProvider allows you to configure and manage a centralized Axios instance for all your API requests. If no configuration is provided, a default instance is used. Alternatively, you can explicitly pass an instanceConfig argument to the useApi hook to override the default or context-provided instance. Example:

import { useEffect } from 'react'
import { ApiClientProvider, useApi } from 'useipa';

const apiClientConfig = {
  baseURL: 'https://api.example.com',
  headers: {
    Authorization: 'Bearer YOUR_ACCESS_TOKEN',
  },
};

const App = () => {
  return (
    <ApiClientProvider client={apiClientConfig}>
      <YourComponent />
      <AnotherComponent />
    </ApiClientProvider>
  );
};

const YourComponent = () => {
  const { fetching, data, error, fetchData } = useApi();

  useEffect(() => {
    fetchData('/users');
  }, []);

  if (fetching) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return <div>Data: {JSON.stringify(data)}</div>;
};

const AnotherComponent = () => {
  const customConfig = { baseURL: 'https://custom-api.example.com' };
 // override ApiClientProvider Instance
  const { fetching, data, error, fetchData } = useApi(customConfig);

  useEffect(() => {
    fetchData('/users');
  }, []);

  if (fetching) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return <div>Data: {JSON.stringify(data)}</div>;
};

export default App;

useFormApi Hook

The useFormApi hook is designed for handling form submissions.

  • Extends useApi with a submitForm method for form submissions.
  • Inherits state management for data, error, fetching, and success from useApi.

Example: Form Submission

import { useState } from 'react'
import { useFormApi } from 'useipa'

const FormComponent = () => {
  const [formData, setFormData] = useState({ name: '', email: '' })
  const { data, success, error, submitForm } = useFormApi()

  const handleChange = (e) => {
    const { name, value } = e.target
    setFormData({ ...formData, [name]: value })
  }

  const handleSubmit = (e) => {
    e.preventDefault()
    submitForm('/api/form', formData)
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="name" value={formData.name} onChange={handleChange} />
      <input type="email" name="email" value={formData.email} onChange={handleChange} />
      <button type="submit">Submit</button>
      {success && <p>Form submitted successfully!</p>}
      {error && <p>Error: {error.message}</p>}
      {data && (
        <div>
          <h1>Response</h1>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      )}
    </form>
  )
}

export default FormComponent

asyncApi Function

  • The asyncApi function allows for simple asynchronous API calls.
  • Allows making direct API calls without using the state management features of useApi.
  • Useful for cases where you don't need to manage state within a React component.

Example: Async API Call

const getUsers = async () => {
  const data = await asyncApi('/api/users')
  console.log(data)
}

or

import { useEffect, useState } from 'react'
import { asyncApi } from 'useipa'

const AsyncComponent = () => {
  const [data, setData] = useState(null)
  const [error, setError] = useState(null)

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await asyncApi('/api/data')
        setData(response)
      } catch (err) {
        setError(err)
      }
    }

    fetchData()
  }, [])

  if (error) return <p>Error: {error.message}</p>
  return (
    <div>
      <h1>Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  )
}

export default AsyncComponent

API Reference

useApi

  • State:

    • data: The response data from the API.
    • fetching: A boolean indicating if the request is in progress.
    • error: An error object if the request fails.
    • success: A boolean indicating if the request was successful.
  • Parameters:

    • instanceConfig? : AxiosInstanceConfig
  • Methods:

  • fetchData(endpoint, config?): Fetches data from an API endpoint. - endpoint: The URL of the API endpoint. - config (optional): An object containing configuration options like headers or method (defaults to GET).

  • mutate(endpoint, data, config?): Mutates data on an API endpoint.

    • endpoint: The URL of the API endpoint.
    • data: The data to be sent for mutation.
    • config (optional): An object containing configuration options like headers or method (defaults to POST).
  • submitApi(endpointOrConfig, config?) (internal method): Handles the actual API request.

    • endpointOrConfig: Either a string representing the endpoint URL or a configuration object.
    • config (optional): Additional configuration options for the request.

useFormApi

  • State and Methods: Inherits all state and methods from useApi.
  • Parameters:
    • instanceConfig? : AxiosInstanceConfig
  • Methods:
    • submitForm(endpoint: string, inputData: object,config?): Submit form data to the specified endpoint using the POST method.

asyncApi

  • Parameters:

    • endpoint: string: The API endpoint to call.
    • method?: string: The HTTP method to use (default is 'GET').
    • config?: RequestConfig: Additional configuration options for the request
  • Returns: A promise that resolves with the API response data.

Request Configuration

The createConfig function (not directly exported) helps build request configurations. You can provide custom configurations when calling fetchData, mutate, or passing them to submitApi and submitForm:

const config = {
  headers: {
    Authorization: `Bearer ${myAuthToken}`,
  },
}

fetchData('/api/data', config)

Error Handling

useApi logs errors to the console by default. You can implement custom error handling in your component. The error property in useApi and useFormApi stores the error object for programmatic handling.

Contributing

If you encounter any issues or have suggestions for improvements, please open an issue or submit a pull request on GitHub.

Conclusion

The useipa package simplifies API interactions in React applications, providing a robust and easy-to-use set of hooks for data fetching and form submission. For more detailed usage and advanced configurations, refer to the provided examples and API reference.

License

This package is licensed under the MIT License. See the LICENSE file for more information.