0.3.0 • Published 1 year ago

triplex-suspense v0.3.0

Weekly downloads
-
License
-
Repository
github
Last release
1 year ago

triplex-suspense - A suspense interface for React

ℹ️ This package is currently in an experimental stage.

triplex-suspense provides an alternative suspense mechanism for React based on the triplex-fp type class, a fp-ts-style representation triply branched UI data state of "progress" (data is being fetched), "error" (the fetching failed) and "available" (the fetching is successful, yielding a result).

You create a suspense interface with createSuspense. This returns an object with a Suspense component and a suspended HOC.

import { constTrue } from "fp-ts/es6/function.js";
import React, { useEffect, useState } from "react";
import { available, progress, Triplex } from "triplex-fp/Triplex";
import { semigroup, Unit, unit } from "triplex-fp/Unit";
import { createSuspense } from "triplex-suspense";

const { Suspense: Mask, suspended } = createSuspense(
  { ...semigroup, equals: constTrue },
  { ...semigroup, equals: constTrue },
  unit
);

function Root() {
  return (
    <Mask
      // Optional, overrides the deflicker interval.
      deflicker={1000}
    >
      <Content queryString={window.location.search} />
    </Mask>
  );
}

const Content = suspended(
  // The suspended data provider function.
  // These props will become the resulting component props.
  (props: { queryString: string }) => {
    const [state, setState] = useState<
      Triplex<Unit, Unit, Triplex<Unit, Unit, string>>
    >(progress(unit));
    useEffect(() => {
      setState(progress(unit));
      fetch(`https://httpbin.org/get?${props.queryString}`)
        .then((response) => response.text())
        .then((result) => setState(available(available(result))));
    }, [props.queryString]);
    return state;
  },
  // The render function.
  // First argument is the resolved triplex value
  // Second argument is the component props.
  (data, { queryString }) => (
    <div>
      <pre>${"Query string: " + queryString}</pre>
      <pre>${"Response:\n" + data}</pre>
    </div>
  )
);

The suspended higher-order-component (HOC) constructs a component that contributes suspended data by forcing you to split your component logic into the data provision function and the render function. The data provision function can return any arbitrary data, where it will be deeply Triplex-sequenced. If the resulting Triplex is in the "available" branch, the render function will be executed and child components will be rendered.

Both functions run in their own isolation context, and both may use hooks, even if sometimes the render function is not executed.

0.3.0

1 year ago

0.2.2

1 year ago

0.2.1

1 year ago

0.2.0

1 year ago

0.1.0

1 year ago