DEV Community

Andreas Iosifelis
Andreas Iosifelis

Posted on

React Ajax Client

react-ajax-client

Consume rest endpoints using react components. Inspired by ApolloClient

NPM JavaScript Style Guide

Install

npm install --save react-ajax-client
Enter fullscreen mode Exit fullscreen mode
yarn add react-ajax-client
Enter fullscreen mode Exit fullscreen mode

Usage

import React from "react";

import { Provider, Fetch, Send, Client } from "react-ajax-client";

const client = new Client({
    baseURL: "http://mywebsite.com/api",
    headers: {
        "Content-Type": "application/json"
    }
});

const ListUsers = () => (
    <Fetch path="/users">
        {({ loading, error, data }) => {
            if (loading) {
                return <div>Loading...</div>;
            }

            if (error) {
                return <div>{error.message}</div>;
            }
            return <pre>{JSON.stringify(data, null, 4)}</pre>;
        }}
    </Fetch>
);

const CreateUser = () => (
    <Send
        path="/users"
        onProgress={() => console.log("Processing")}
        onComplete={response =>
            console.log("Completed", JSON.stringify(response))
        }
        onError={response => console.error("Error", JSON.stringify(response))}
    >
        {trigger => (
            <button
                onClick={e => trigger({ firstName: "Billy", lastName: "Jean" })}
            >
                Create a User
            </button>
        )}
    </Send>
);

const MyApp = () => (
    <Provider client={client}>
        <div>
            <h1>My App</h1>
            <CreateUser />
            <ListUsers />
        </div>
    </Provider>
);
Enter fullscreen mode Exit fullscreen mode

Check out the Code

Top comments (0)