Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/devtools-extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"cra-template": "1.1.2",
"lodash": "^4.17.21",
"react": "18.1.0",
"react-async-states": "1.0.0-rc-1.1",
"react-async-states": "1.0.0-rc-2",
"react-dom": "18.1.0",
"react-json-view": "^1.21.3",
"react-scripts": "4.0.3"
Expand Down
2 changes: 1 addition & 1 deletion packages/example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"lodash": "^4.17.21",
"prop-types": "^15.6.2",
"react": "18.1.0",
"react-async-states": "1.0.0-rc-1.1",
"react-async-states": "1.0.0-rc-2",
"react-dom": "18.1.0",
"react-router-dom": "6.4.0-pre.2",
"react-scripts": "4.0.3"
Expand Down
67 changes: 67 additions & 0 deletions packages/example/src/App2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import React from "react";
import {
RenderStrategy,
StateBoundary,
useCurrentState,
AsyncStateStatus
} from "react-async-states";

const config = {
lazy: false,
producer: async function () {
const response = await fetch('https://jsonplaceholder.typicode.com/users/12');
if (!response.ok) {
throw new Error(response.status);
}
return response.json();
}
}

function Wrapper({children}) {
const [t, e] = React.useState(false);

return (
<>
<button onClick={() => e(f => !f)}>Toggle</button>
{t && children}
</>
)
}

function MyError() {
const {state: {data: error}} = useCurrentState();

return <div>This error is happening: {error?.toString?.()}</div>
}

function MyPending() {
const {state: {props}} = useCurrentState();

return <div>PENDING WITH PROPS: {JSON.stringify(props, null, 4)}</div>
}

export default function App2() {
return (
<Wrapper>
<h1>Result!</h1>
<StateBoundary
config={config}
strategy={RenderStrategy.FetchThenRender}
render={{
[AsyncStateStatus.error]: <MyError/>,
[AsyncStateStatus.success]: <CurrentState/>,
}}
/>
</Wrapper>
);
}

function CurrentState() {
const currentState = useCurrentState();
return <details open>
<summary>Current state details {currentState.state.status}</summary>
<pre>
{JSON.stringify(currentState, null, 4)}
</pre>
</details>
}
2 changes: 1 addition & 1 deletion packages/example/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react'
import ReactDOM from 'react-dom/client'

import './index.css'
import App from "./past/App";
import App from "./App2";

// import App2 from './past/App2';

Expand Down
2 changes: 1 addition & 1 deletion packages/react-async-states/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"types": "dist/react-async-states/src/index",
"author": "incepter",
"sideEffects": false,
"version": "1.0.0-rc-1.1",
"version": "1.0.0-rc-2",
"name": "react-async-states",
"repository": "incepter/react-async-states",
"description": "A hooks-based lightweight React library for state management",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@ import {UseAsyncState} from "../../../../../types.internal";
import {AsyncStateStatus} from "../../../../../async-state";
import {mockDateNow, TESTS_TS} from "../../../utils/setup";

jest.useFakeTimers();
mockDateNow();

describe('should post subscribe', () => {
it('should invoke post subscribe when present and run producer' +
' and run post unsubscribe', async () => {
jest.useFakeTimers();
// given
const onAbort = jest.fn();
const producer = jest.fn().mockImplementation(props => {
Expand Down
3 changes: 2 additions & 1 deletion packages/react-async-states/src/async-state/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,9 @@ export enum ProducerType {
}

export enum RenderStrategy {
FetchOnRender = 0,
FetchAsYouRender = 0,
FetchThenRender = 1,
RenderThenFetch = 2,
}

export type ProducerConfig<T> = {
Expand Down
75 changes: 0 additions & 75 deletions packages/react-async-states/src/components/AsyncStateComponent.tsx

This file was deleted.

126 changes: 126 additions & 0 deletions packages/react-async-states/src/components/StateBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import * as React from "react";
import {
AsyncStateSource,
AsyncStateStatus,
RenderStrategy,
State
} from "../async-state";
import {
AsyncStateSubscriptionMode,
StateBoundaryProps,
UseAsyncState,
} from "../types.internal";
import {useAsyncState} from "../hooks/useAsyncState";
import {readAsyncStateFromSource} from "../async-state/read-source";

const StateBoundaryContext = React.createContext<any>(null);

export function StateBoundary<T, E>(props: StateBoundaryProps<T, E>) {
return (
<StateBoundaryImpl key={props.strategy} {...props}>
{props.children}
</StateBoundaryImpl>
)
}

function StateBoundaryImpl<T, E>(props: StateBoundaryProps<T, E>) {
if (props.strategy === RenderStrategy.FetchThenRender) {
return React.createElement(FetchThenRenderBoundary, props);
}
if (props.strategy === RenderStrategy.FetchAsYouRender) {
return React.createElement(FetchAsYouRenderBoundary, props);
}
return React.createElement(RenderThenFetchBoundary, props);
}

function inferBoundaryChildren<T, E = State<T>>(
result: UseAsyncState<T, E>,
props: StateBoundaryProps<T, E>
) {
if (!props.render || !result.source) {
return props.children;
}

const asyncState = readAsyncStateFromSource(result.source);
const {status} = asyncState.currentState;

return props.render[status] ? props.render[status] : props.children;
}

export function RenderThenFetchBoundary<T, E>(props: StateBoundaryProps<T, E>) {
const result = useAsyncState(props.config, props.dependencies);

const children = inferBoundaryChildren(result, props);
return (
<StateBoundaryContext.Provider value={result}>
{children}
</StateBoundaryContext.Provider>
);
}

export function FetchAsYouRenderBoundary<T, E>(props: StateBoundaryProps<T, E>) {
const result = useAsyncState.auto(props.config, props.dependencies);
result.read(); // throws
const children = inferBoundaryChildren(result, props);
return (
<StateBoundaryContext.Provider value={result}>
{children}
</StateBoundaryContext.Provider>
);
}

type FetchThenRenderSelf = {
didLoad: boolean,
}

export function FetchThenRenderBoundary<T, E>(props: StateBoundaryProps<T, E>) {
const result = useAsyncState.auto(props.config, props.dependencies);
const self = React.useMemo<FetchThenRenderSelf>(constructSelf, []);

if (result.mode === AsyncStateSubscriptionMode.NOOP ||
result.mode === AsyncStateSubscriptionMode.WAITING) {
throw new Error("FetchThenRenderBoundary is not supported with NOOP and WAITING modes");
}

if (!self.didLoad) {
const {source} = result;
const asyncState = readAsyncStateFromSource(source as AsyncStateSource<T>);

const {status} = asyncState.currentState;

if (status === AsyncStateStatus.error || status === AsyncStateStatus.success) {
self.didLoad = true;
const children = inferBoundaryChildren(result, props);
return (
<StateBoundaryContext.Provider value={result}>
{children}
</StateBoundaryContext.Provider>
);
}

return null;
} else {
const children = inferBoundaryChildren(result, props);
return (
<StateBoundaryContext.Provider value={result}>
{children}
</StateBoundaryContext.Provider>
);
}

function constructSelf() {
return {
didLoad: false,
};
}
}

export function useCurrentState<T, E = State<T>>(): UseAsyncState<T, E> {
const ctxValue = React.useContext(StateBoundaryContext);

if (ctxValue === null) {
throw new Error('You cannot use useCurrentState outside a StateBoundary');
}

return ctxValue;
}
8 changes: 7 additions & 1 deletion packages/react-async-states/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@ export {
invalidateCache,
useRunAsyncState,
} from "./hooks/useRun";
export {AsyncStateComponent} from "./components/AsyncStateComponent";
export {
StateBoundary,
useCurrentState,
FetchThenRenderBoundary,
RenderThenFetchBoundary,
FetchAsYouRenderBoundary,
} from "./components/StateBoundary";
export {useSelector, useAsyncStateSelector} from "./hooks/useSelector";

export * from "./types";
16 changes: 15 additions & 1 deletion packages/react-async-states/src/types.internal.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as React from "react";
import {
AbortFn,
AsyncStateInterface,
Expand All @@ -9,11 +10,12 @@ import {
Producer,
ProducerConfig,
ProducerProps,
ProducerRunEffects,
ProducerRunEffects, RenderStrategy,
RunExtraProps,
State,
StateUpdater
} from "./async-state";
import {ReactNode} from "react";

export type Reducer<T> = (
T,
Expand Down Expand Up @@ -261,6 +263,18 @@ export type UseAsyncStateConfiguration<T, E = State<T>> = {
lane?: string,
}

export type StateBoundaryProps<T, E> = {
children: React.ReactNode,
config: UseAsyncStateConfig<T, E>,

dependencies?: any[],
strategy?: RenderStrategy,

render?: StateBoundaryRenderProp,
}

export type StateBoundaryRenderProp = Record<AsyncStateStatus, ReactNode>

export type UseAsyncStateEventProps<T> = {
state: State<T>,
};
Expand Down
3 changes: 3 additions & 0 deletions packages/react-async-states/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export type {
} from "./async-state/types";

export {
RenderStrategy,
ProducerRunEffects,
} from "./async-state/types";

Expand Down Expand Up @@ -41,4 +42,6 @@ export type {
UseAsyncStateEventFn,
UseAsyncStateEventProps,

StateBoundaryProps,

} from "./types.internal";