Coder Social home page Coder Social logo

react-request-hook-client's Introduction

react-request-hook-client

A helper react component to make HTTP requests, powered by React Hooks, insipred by Apollo GraphQL Query component. It supports both declarative and hooks ways.

Installing

npm

$ npm install --save react-request-hook-client

or Yarn

$ yarn add react-request-hook-client

Requirements

React >= 16.8.0

Get Started

See live example on CodeSandBox:

Edit react-request-hook-client-demo2

use <Request /> component

GET

import { Request, useRequest } from "react-request-hook-client";

function App() {
  return (
      <Request url="https://jsonplaceholder.typicode.com/todos/1">
        {({ data }) => {
          return <div>Get using declarative way: {JSON.stringify(data || {})}</div>;
        }}
      </Request>
  );
}

POST and others

function PostDemo() {
  return (
    <>
      <div>declarative post: </div>
      <Request
        method="POST"
        url="https://jsonplaceholder.typicode.com/posts"
        variables={{ userId: 2, title: "foo", body: "bar" }}
      >
        {(doRequest, { loading, error, data }) => {
          return (
            <>
              <div>loading: {`${loading}`}</div>
              <div>data: {JSON.stringify(data || {})}</div>
              <div>error: {JSON.stringify(error || {})}</div>
              <button
                onClick={() => {
                  doRequest();
                }}
              >
                Send request
              </button>
            </>
          );
        }}
      </Request>
    </>
  );
}

Use Hooks

GET

function GetHooksDemo() {
  const { error, loading, data } = useRequest({
    url: "https://jsonplaceholder.typicode.com/todos/2"
  });

  if (loading) return <div>loading...</div>;
  if (error) return null;
  return <div>hooks way: {JSON.stringify(data)}</div>;
}

POST and others

function PostDemoHooks() {
  const { doRequest, error, loading, data } = useRequest({
    url: "https://jsonplaceholder.typicode.com/posts",
    method: "POST",
    variables: {
      userId: 1
    }
  });

  return (
    <>
      <div>Post Hook</div>
      <div>loading: {`${loading}`}</div>
      <div>data: {JSON.stringify(data || {})}</div>
      <div>error: {JSON.stringify(error || {})}</div>
      <button
        onClick={() => {
          doRequest({ title: "foo", body: "bar" });
        }}
      >
        Send request
      </button>
    </>
  );
}

API

Request component

Props

Props Type Default Value Description
url String The HTTP request url
method String GET The HTTP request method, supports GET, POST, PUT, DELETE
variables Object Variables for the request. If it is a GET request, variables will be converted to query strings. If it is a POST/PUT/DELETE request, variables will be the request body.
headers Object {"Content-Type": "application/json"} Additional headers
fire Boolean TRUE Whether to fire the request immediately, used to finely control the time when the request will fire.
onSuccess (data) => Void Called on request successfully returned
onError (error) => Void Called on error ocurred during the request
onComplete () => Void Called on request finished, whether it succeeded or failed

The children passed to the <Request/> component must be a function, it has the following signature when the request method is GET:

({loading, error, data, doRequest}) => {

  return // a react component

}

POST and others:

(doRequest, {loading, error, data}) => {

  return // a react component

}

Arguments explanation:

  • loading - Whether the request is pending.
  • error - Error details when request encounters HTTP errors.
  • data - Data returned by the server.

The function MUST return a single React component according to JSX rules, or null if no component will be returned.

useRequest hook

The useRequest hook takes the same props/arguments as the <Request/> component does, and returns the following object upon using:

  const { loading, error, data, doRequest } = useRequest({url:, variables:, ...})

In addition to specify variables at the declaration time, the doRequest function also takes an additional variables object as its argument:

<button
  onClick={() => {
    doRequest({ title: "foo", body: "bar" });
  }}
>
  Send request
</button>

It also has return values, which are:

  • { success: true, response } - when the HTTP request succeeds.
  • { success: false, error } - when the HTTP request fails.

These values can help users to deal with response data at the time when the event triggers.

Issues

If you have any questions or find a bug of this library, please feel free to open an issue.

License

MIT

react-request-hook-client's People

Contributors

zxuqian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

jackjunjie

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.