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

@sinoui/use-data-api

v1.0.3

Published

[![npm version](https://img.shields.io/npm/v/@sinoui/use-data-api)](https://www.npmjs.com/package/@sinoui/use-data-api) [![downloads](https://img.shields.io/npm/dm/@sinoui/use-data-api)](https://www.npmjs.com/package/@sinoui/use-data-api)

Downloads

8

Readme

@sinoui/use-data-api

npm version downloads

使用 React Hooks 实现数据加载的库。

安装

yarn add @sinoui/use-data-api

或者

npm i --save @sinoui/use-data-api

使用

简单示例:

import React, { useState } from 'react';
import useDataApi from '@sinoui/use-data-api';

interface User {
  userId: string;
  userName: string;
}

function UserList() {
  const { data, isLoading, isError, doFetch } = useDataApi<User[]>(
    '/users',
    [],
  );

  return (
    <div>
      {isLoading && <div>正在加载数据</div>}
      {isError && <div>加载数据失败</div>}
      <ul>
        {data.map((user) => (
          <li key={user.id}>{user.userName}</li>
        ))}
      </ul>
    </div>
  );
}

查询示例:

import React, { useState } from 'react';
import useDataApi from '@sinoui/use-data-api';

interface User {
  userId: string;
  userName: string;
}

function UserList() {
  const [searchText, setSearchText] = useState('');
  const { data, isLoading, isError, doFetch } = useDataApi<User[]>(
    '/users',
    [],
  );

  const handleSearch = () => {
    doFetch(`/users?text=${searchText}`);
    setSearchText('');
  };

  return (
    <div>
      <form>
        <label>姓名</label>
        <input
          type="text"
          value={searchText}
          onChange={(event) => setSearchText(event.target.value)}
        />
        <button onClick={handleSearch}>查询</button>
      </form>
      {isLoading && <div>正在加载数据</div>}
      {isError && <div>加载数据失败</div>}
      <ul>
        {data.map((user) => (
          <li key={user.id}>{user.userName}</li>
        ))}
      </ul>
    </div>
  );
}

另外一个加载 Hacker News 的例子:

例子源码例子效果

方法说明

import useDataApi from '@sinoui/use-data-api';

interface DataSource<T> {
  /**
   * 从API中获取到的数据
   */
  data: T;
  /**
   * 数据加载中状态。`true`表示数据加载中。
   */
  isLoading: boolean;
  /**
   * 数据加载失败状态。`true`表示数据加载失败。
   */
  isError: boolean;
  /**
   * 加载数据
   *
   * @param {string} url 获取数据的url
   * @param {boolean} forceFetch 当指定的`url`与上一次请求的`url`一致时,是否发送API请求。
   *                              默认为`true`,表示发送请求。
   */
  doFetch: (url?: string, forceFetch?: boolean) => void;

  /**
   * 重新加载数据
   */
  reload: () => void;

  /**
   * 更新数据
   */
  setData: (data: T) => void;
}

/**
 * 数据加载hook
 *
 * @template T
 * @param {string} defaultUrl 默认加载数据的链接
 * @param {T} defaultValue 默认数据
 * @param {HttpRequestConfig} httpRequestConfig 请求配置
 * @returns {DataSource<T>}
 */
function useDataApi<T>(
  defaultUrl: string | undefined,
  defaultValue: T,
  httpRequestConfig: HttpRequestConfig,
): DataSource<T>;

默认通过GET方法发送 API 请求,获取到的响应数据直接作为dataSource.data。可以通过httpRequestConfig来调整,如下所示:

const transformResponse = (data) => data.map((item) => item.userName); // 将人员信息列表转换成人名列表

const dataSource = useDataApi('/users', [], {
  transformResponse,
  method: 'POST',
});

更多请求配置参见Axios Request Config

注意:如果url为空(''nullundefined)时,则不会发送 API 请求。