Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ncpa0cpl/react-promised-state
https://github.com/ncpa0cpl/react-promised-state
Last synced: about 10 hours ago
JSON representation
- Host: GitHub
- URL: https://github.com/ncpa0cpl/react-promised-state
- Owner: ncpa0cpl
- Created: 2021-06-10T20:02:00.000Z (over 3 years ago)
- Default Branch: master
- Last Pushed: 2022-01-05T12:03:44.000Z (almost 3 years ago)
- Last Synced: 2024-11-03T06:09:46.362Z (14 days ago)
- Language: TypeScript
- Size: 265 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# React Use Promised State Hook
React Hook for storing state that's updated asynchronously.
## Usage
`usePromisedState` hook can accept a value, a function returning a value or a function returning a Promise resolving a value as it's initial parameters and as SetStateAction argument, SetStateAction argument can additionally be a regular Promises.
`usePromisedState` returns a 2-tuple with a PromisedState object and a SetStateAction dispatch function.
PromisedState object structure is as seen here:
```ts
type PromisedState = {
isPending: boolean;
data: T | null;
error: Error | null;read(): T;
};
```- `PromisedState.isPending` is a boolean indicating if the last provided SetStateAction Promise is resolved/rejected (false) or is still pending (true). Is always false if the last SetStateAction is not a Promise.
- `PromisedState.data` holds the actual state value. It is not set to empty when a dispatched promise is pending.
- `PromisedState.error` holds the error rejected by the last dispatched Promise or SetStateAction function. It is not set to empty when a dispatched promise is pending.
- `PromisedState.read()` is a function that returns the value stored in the `data` property if no error is present and not pending. If a dispatched promise is pending it will throw that promise. If an error is present it will throw that error. It's intended to be used with the React.Suspense component.
### Initiation
`usePromisedState` accepts one of the three initial value types:
- regular value, like a string, number, array or object
```ts
const [state, setState] = usePromisedState("value"); // state: PromisedState
// or
const [state, setState] = usePromisedState(123); // state: PromisedState
```- a generator function returning a regular value
```ts
const [state, setState] = usePromisedState(() => ["value"]); // state: PromisedState
// or
const [state, setState] = usePromisedState(() => new Set()); // state: PromisedState>
```- a generator function returning a Promise
```ts
const [state, setState] = usePromisedState(() => Promise.resolve({ foo: "foo" })); // state: PromisedState<{ foo: string }>
// or
const [state, setState] = usePromisedState(() => Promise.resolve([1, 2, 3])); // state: PromisedState
```### SetStateAction Dispatch Function
The dispatch function of the promised state can accept:
- regular value like a string, number, array or object
```ts
const [state, setState] = usePromisedState(); // state: PromisedStatesetState("hello world");
```- a generator function returning a regular value
```ts
const [state, setState] = usePromisedState(); // state: PromisedStatesetState((currentState: PromisedState) => ["foo", "bar", "baz"]);
```- a generator function returning a Promise
```ts
const [state, setState] = usePromisedState<{ foo: string }>(); // state: PromisedState<{ foo: string }>setState((currentState: PromisedState<{ foo: string }>) => Promise.resolve({ foo: "foo bar baz" }));
```- a Promise
```ts
const [state, setState] = usePromisedState>(); // state: PromisedState>setState(Promise.resolve(new Set([1, 2, 3])));
```## Examples
```tsx
import { usePromisedState } from "react-promised-state";// Method for retrieving a string value from some API
const getTitleFromApi = (): Promise => {
return fetch("www.your-api-url.com", { method: "GET" }).then((resp) => resp.text());
};const Component: React.FC = () => {
// Use hook and set an initial value
const [title, setTitle] = usePromisedState("Initial Value");React.useEffect(() => {
// fetch data and update the state
setTitle(getTitleFromApi());
}, []);if (title.isPending)
Loading...;
else if (title.error) returnAn error occurred!;
else return{title.data};
};
```### React Suspense
`usePromisedState` supports the React Suspense component.
To use it with it usePromisedState should be located in a component outside the Suspense boundary and passed via props to a component within the Suspense boundary and there a `.read()` method should be called on the Resource object.
#### Example
```tsx
import { usePromisedState } from "react-promised-state";
import type { SuspenseReader } from "react-promised-state";// Method for retrieving a string value from some API
const getTitleFromApi = (): Promise => {
return fetch("www.your-api-url.com", { method: "GET" }).then((resp) => resp.json());
};const DisplayTitle: React.FC<{ title: SuspenseReader }> = ({ title }) => {
return{title.read()};
};const Component: React.FC = () => {
// Set a generator that will fetch the title as the initial value
const [title, setTitle] = usePromisedState(() => getTitleFromApi());return (
Loading...}>
);
};
```## License
#### MIT