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-standardapi

v1.0.15

Published

A React library for querying a Rails application through StandardAPI.

Downloads

31

Readme

React StandardAPI

A React library for querying a Rails application through StandardAPI. Requires StandardAPI Client and React as peer dependencies.

Installation

Using npm:

$ npm install react-standardapi standardapi-client

Using yarn:

$ yarn add react-standardapi standardapi-client

Implementation

First the StandardAPI Client must be instantiated. Headers are optional.

import StandardAPIClient from 'standardapi-client'

const client = new StandardAPIClient({
  baseURL: API_BASE_URL,
  headers: {
    'Api-Key': API_KEY,
    'Api-Version': API_VERSION,
  }
})

Then, the React application must be wrapped in the <StandardAPIProvider /> component which passes the StandardAPI client instance to the app through React context. Then you are able to use the <Read /> component which retrieves data from StandardAPI.

import { StandardAPIProvider } from 'react-standardapi'
import ReactDOM from 'react-dom'

params = {
  limit: 10,
  offset: 0,
  where: {
    status: 'INCOMPLETE'
  }
}

const app = () => (
  <StandardAPIProvider client={client}>
    <Read baseModel='todos' params={params}>
    {({ data, loading, error, refetch }) => {
      if (loading) return renderLoading()
      if (error) return renderError(error)
      return (
        <div>
          { data.map(t => renderTodoItem(t, refetch)) }
          <button onClick={refetch}>Reload</button>
        </div>
      )
    }}
    </Read>
  </StandardAPIProvider>
)

ReactDOM.render(app, document.getElementById('root'))

Read

The children of the <Read /> component receive four props. The loading prop is a boolean indicating whether the request has completed or is still in flight. The error prop is the error object in the event the request fails. The data is the response payload of a successful request, and refetch is a function that retriggers the StandardAPI call.

Data can be mutated using the client's create, update, and destroy methods and the data can be refetched using the refetch function. For example, consider the renderTodoItem function below.

const renderTodoItem = (t, refetch) => (
  <div>
  	<h1>{ t.name }</h1>
  	<p>{ t.description }</p>
  	<button onClick={() => deleteTodo(t.id, refetch)}
  </div>
 )
 
 const deleteTodo = async (id, refetch) => {
   try {
 	  await client.destroy('todos', id)
 	  refetch()
   } catch (e) {
 	  handleError(e)
 	}
 }
    

In the above example, we use the StandardAPI client to delete a todo and then use the refetch function to refresh the list of todos.

BatchedLoader

If you want to load data dynamically using pagination, you can use the <BatchedLoader /> component. The batchSize prop sets the number of records returned in each batched load.

const Newsfeed = () => (
  <StandardAPIProvider client={client}>
    <BatchedLoader baseModel='articles' params={{ include: { author: true }}} batchSize={5}>
      {({ data, error, fetchNextBatch }) => {
        if (error) return <div>Error...</div>

        return (
          <div>
            {
              data.map(a => {
                if (a.loading) return <ArticleLoader />
                else return <ArticleCard article={a} />
              })
            }
            <button onClick={fetchNextBatch}>Load More Articles</button>
          </div>
        )
      }}
    </BatchedLoader>
  </StandardAPIProvider>
)

The <BatchedLoader /> component returns loading objects (e.g. { loading: true, index: 3 }) while the query is loading which allows for rendering dummy UI before the content loads. Calling the fetchNextBatch function adds the next batch of loading objects onto the data array. When the query is resolved, the loading objects are replaced with the records returned from the StandardAPI call.

Resources

Credits

React StandardAPI is heavily inspired by the GraphQL client library Apollo Client. Ultimately, React StandardAPI is an effort to provide an Apollo Client-like developer experience for StandardAPI.

License

MIT