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-net-kit

v1.0.3

Published

Simplify HTTP and WebSocket requests in React with this versatile package.

Downloads

51

Readme

react-net-kit

Simplify HTTP and WebSocket requests in React with this versatile package.

npm package


Features

  • Seamless React.Suspense integration.
  • Lightweight and efficient.
  • Supports both automatic and manual requests.
  • Fully customizable to fit your needs.
  • Powered by Axios for reliable HTTP requests.
  • Manage multiple instances effortlessly.

Installation

Choose your preferred package manager to get started:

npm

shellCopy code

npm i react-net-kit axios

yarn

shellCopy code

yarn add react-net-kit axios

pnpm

shellCopy code

pnpm add react-net-kit axios


Setup

Configure your application with the desired settings.

Basic Usage:

api.js

import ReactNetKit from 'react-net-kit'
export const { useApi, useApiOnce, createSuspense } = ReactNetKit()

Component.js

import { useApiOnce } from './api.js'

const Component = () => {
  const api = useApiOnce({ get: 'https://www.boredapi.com/api/activity' })
  const [bored] = api.responses

  if (api.loading) return <div>'Loading...'</div>
  if (bored.error) return <div>{bored.error}</div>
  return <div>{bored.data.activity}</div>
}
import { useApi } from './api.js'

const Component = () => {
  const api = useApi()

  const handleClick = async () => {
    const { data, ok } = await api.get('https://www.boredapi.com/api/activity')
    console.log(data)
  }

  if (api.loading) return <div>'Loading...'</div>
  if (api.response.error) return <div>{api.response.error}</div>
  return (
    <button onClick={handleClick}>
      {api.response.data ?? 'Click me to get a message'}
    </button>
  )
}
import { useState } from 'react'
import { createSuspense } from './api.js'

const useSuspense = createSuspense()
const Component = () => {
  const api = useApi()

  const handleClick = async () => {
    const { data, ok } = await api.get('https://www.boredapi.com/api/activity')
    console.log(data)
  }

  if (api.loading) return <div>'Loading...'</div>
  if (api.response.error) return <div>{api.response.error}</div>
  return (
    <button onClick={handleClick}>
      {api.response.data ?? 'Click me to get a message'}
    </button>
  )
}

Advanced Usages of ReactNetKit:

ReactNetKit(AxiosInstanceConfig && ReactNetKitConfig)

Check the Axios instance config for AxiosInstanceConfig.


ReactNetKitConfig Options:

{
  formatData?: (response: AxiosResponse) => formattedData,
  formatError?: (err: AxiosError) => formattedError,
}

Options formatData and formatError:

These options accept AxiosResponse or AxiosError as the first argument and return the desired formatted data or error.

Example:

ReactNetKit({
  formatData: (response) => {
    return response.status === 204 ? true : response.data?.data ?? response.data
  },

  formatError: (err) => {
    return err.response?.data?.message ?? err.message
  },
})

ReactNetKit().axios:

Access the raw Axios instance.

ReactNetKit().methods:

This object provides various HTTP request methods, all of which return {error, data, ok}:

{
  requests: async Function,
  request: async Function,
  get: async Function,
  delete: async Function,
  head: async Function,
  options: async Function,
  post: async Function,
  put: async Function,
  patch: async Function,
}

All functions accept Axios parameters; refer to the Axios instance config for details.

ReactNetKit().useApi(config):

Usage Examples:

import { useApi } from './api.js'

const Component = () => {
  const api = useApi()

  const handleClick = async () => {
    const { data, ok } = await api.get('https://www.boredapi.com/api/activity')
    console.log(data)
  }

  if (api.loading) return <div>'Loading...'</div>
  if (api.response.error) return <div>{api.response.error}</div>
  return (
    <button onClick={handleClick}>
      {api.response.data ?? 'Click me to get a message'}
    </button>
  )
}

ReactNetKit().useApiOnce(...axios, onLoad):

import { useApi } from './api.js'

const Component = () => {
  const api = useApi()

  const handleClick = async () => {
    const { data, ok } = await api.get('https://www.boredapi.com/api/activity')
    console.log(data)
  }

  if (api.loading) return <div>'Loading...'</div>
  if (api.response.error) return <div>{api.response.error}</div>
  return (
    <button onClick={handleClick}>
      {api.response.data ?? 'Click me to get a message'}
    </button>
  )
}

ReactNetKit().createSuspense():

This function returns a hook that utilizes React.Suspense. Please create a new hook for each component to avoid conflicts.

import { createSuspense } from './api.js'
const useSuspenseApi = createSuspense()
const useSuspenseApi2 = createSuspense({ cache: true })

const Component = () => {
  // Basic usage
  const [bored, dummy] = useSuspenseApi(
    { url: 'https://www.boredapi.com/api/activity' },
    { url: 'https://dummyjson.com/products' }
  )

  // With a callback function
  const api2 = useSuspenseApi2(
    { url: 'https://www.boredapi.com/api/activity' },
    { url: 'https://dummyjson.com/products' },
    ([bored, dummy]) => {
      // This onLoad function is called once when the data loads for the first time
      console.log(bored.data, dummy.data)
    }
  )

  return <div>{bored.data.activity}</div>
}

What about AbortController?

While adding AbortController, consider the potential performance impact.

import { useSignal } from 'react-net-kit'
import { useApi } from './api.js'

const Component = () => {
  const api = useApi()
  const [signal, abort, isActive] = useAbortSignal()

  const handleSearch = async (e) => {
    const res = await api.get('/user/search', {
      signal: signal(),
    })
  }
}

Wait a minute, what about WebSocket?

ws.js

import ReactWs from 'react-net-kit/ws'
import { io } from 'socket.io-client'

const socket = io('http://localhost:8000')

socket.on('connect', () => {
  console.log('connected')
})

export const { useWs, useDataWs } = ReactWs(socket, {
  checkData(res) {
    return res.status === 'success'
  },
  formatData(res) {
    return res.data ?? res
  },
  formatError(res) {
    return res.message ?? res
  },
})

App.js

import { useWs } from './ws'

const App = () => {
  const ws = useWs({ suspense: true })

  const handleClick = async () => {
    // This works similar to useApi().request but for WebSocket!
    const [res] = await ws.send('hello')
    console.log(res)
  }

  const handleClick = async () => {
    // This works similar to useApi().requests
    const [res1, res2] = await ws.send('hello')
    console.log(res1, res2)
  }

  return <button onClick={handleClick}>Click</button>
}

Made with ❤️ by Nazmus Sayad.