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-async-comp

v0.2.11

Published

RAC is a library used for rendering components with asynchronous data.

Downloads

10

Readme

React Async Component

RAC is a library used for rendering components with asynchronous data.

Getting started

Installation

Using npm

npm i react-async-comp

Using yarn

yarn add react-async-comp

Quick Start Guide

import { Suspense } from "react";
import { ErrorBoundary } from "react-error-boundary";
import { view } from "react-async-comp";

const TodoList = view(async () => {
  // fetching data
  const res = await fetch("https://jsonplaceholder.typicode.com/todos");
  const todos = await res.json();

  // rendering
  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.title}</li>
      ))}
    </ul>
  );
});

const App = () => {
  return (
    <>
      <ErrorBoundary fallback={<div>Something went wrong</div>}>
        <Suspense fallback={<div>Loading...</div>}>
          {/* Even if the component has multiple instances, the data fetching code runs only once */}
          <TodoList />
          <TodoList />
          <TodoList />
        </Suspense>
      </ErrorBoundary>
    </>
  );
};

In the example above, we can use asynchronous data fetching code alongside rendering code. There are important rules to note:

  • Do not use any React hooks inside the data loading function.
  • All component properties must be serializable. Accepted types include: Boolean, String, null, undefined, number, RegExp, Date, PlainObject, and Array.
  • RAC must be used in conjunction with the Suspense and ErrorBoundary components.

Advanced Usages

Using hook with RAC

To use hooks with React Async Component, the view(loader, render) overload must be utilized. The render function accepts component props and RenderContext as parameters. RenderContext consists of the following properties:

  • revalidate: Triggers a revalidation for all instances of the component.
  • data: Represents the data fetched by the loader() function.
const TodoList = view(
  // loader function
  async () => {
    const res = await fetch("https://jsonplaceholder.typicode.com/todos");
    const todos = await res.json();

    return todos;
  },
  // render function
  (props, { data: todos, revalidate }) => {
    // consume hooks or contexts
    const [state, setState] = useState();
    const store = useStore();
    // render function can accept non-serializable
    const handleClick = props.onClick;

    return (
      <ul>
        {todos.map((todo) => (
          <li onClick={handleClick} key={todo.id}>
            {todo.title}
          </li>
        ))}
      </ul>
    );
  }
);

RAC data lifecycle

By default, RAC automatically disposes of fetched data if it is no longer used by any components.

const App = () => {
  const [show, setShow] = useState(true);

  return (
    <>
      <button onClick={() => setShow(!show))>Toggle todo list</button>
      {show && <ErrorBoundary fallback={<div>Something went wrong</div>}>
        <Suspense fallback={<div>Loading...</div>}>
          <TodoList />
        </Suspense>
      </ErrorBoundary>}
    </>
  );
};

When the TodoList is toggled, the todo list data will be disposed if TodoList is unmounted and will be refetched when TodoList is mounted again.

To retain the fetched data indefinitely, the following options can be utilized:

const TodoList = view(loader, { dispose: "never" });

The dispose option accepts two values: never and unused:

  • never: The fetched data is never removed.
  • unused (default): The fetched data will be removed when it is no longer used by any RAC.

Revalidating RAC data

Revalidating RAC data involves re-executing the loader function and performing a re-render of all RAC instances that consume the data.

To revalidate RAC data, you can use one of the following approaches:

  • Utilize the revalidate method from LoaderContext, which is the second argument of the loader function.
  • Employ the revalidate method from RenderContext, provided as the second argument of the render function.
  • Invoke the revalidate method directly on the RAC.
// using revalidate method of LoaderContext
const TodoList = view((props, { revalidate }) => {
  return (
    <>
      <button onClick={revalidate} />
    </>
  );
});

const TodoList = view(
  (props) => todoList,
  // using revalidate methods of RenderContext
  (props, { revalidate }) => {
    return (
      <>
        <button onClick={revalidate} />
      </>
    );
  }
);

// using static revalidate method of RAC
TodoList.revalidate();

Using RAC with external stores

RAC can integrate with external stores, utilizing their data and revalidating whenever the store data changes.

import { store } from "./redux-store";

const TodoList = view((props, { use }) => {
  // When the store state is updated, the loader function will be invoked.
  const { filter } = use(store);
  const todos = await getTodosWithFilter(filter)

  return (<>
    <ul>
      {todos.map((todo) => (
          <li key={todo.id}>
            {todo.title}
          </li>
      ))}
    </ul>
  </>);
});