Skip to content

explodingcamera/react-sus

Repository files navigation

react-sus  

npm i react-sus

Minimal Suspense-based data-fetching (Currently in development and not production-ready)

Example

TypeScript
import { Suspense } from "react";
import { sus } from "react-sus";

interface User {
  username: string;
}

const SomeComponent = ({ userID }: { userID: string }) => {
  const data = sus<User>(`https://api.example.com/user/${userID}`);
  return <div>{data.username}</div>;
};

const App = () => (
  <Suspense fallback={<div>Loading...</div>}>
    <SomeComponent userID={"example"} />
  </Suspense>
);

API

Simplified API
type sus = <Data>(
  key: Key, // anything that can be serialized to a string
  fetcher?: Fetcher | undefined,
  userConfig?: Config
) => Await<Data>;

interface Config {
  fetcher: Fetcher; // any promise or fetch-like function
  cacheProvider: Cache; // any Map-like function
}

Any Component using this function needs to be wrapped in an <Suspense></Suspense> block. Once the promise is started, control will be given back to react until the promise resolves and the actual data is returned.

The key acts as the key for caching the results, so be sure to not reuse the same cache keys for different requests (only relevant when they both use the same cacheProvider).

When an error occours, it will bubble up to the next <ErrorBoundary/>. Because of this, the return value is guaranteed to be valid.

Configuration

Context

will be available at release

Pre-Loading

will be available at release

Cache Busting

will be available at release

Inspirations

This project seeks to combine the simplicity of swr with react-query's feature set and suspend-react's suspense support.

Related Projects

  • snowstorm - The lightning-fast and minimalist React Tool