README
ts-rest-react
ts-rest-react is very small and simple package which provides 2 things:
- A react hook for managing requests
- A react wrapper component for automatic pending and error indication.
useRest - react hook
useRest is a react hook which allowes you to access your request state and data very easily.
It is built upon @abiskup/ts-rest-client but can basically be used with any function that returns a Promise
.
Example
For this example we assume that getName()
is a function that fetches a name from a RESTful service and returns Promise<string>
.
As a result of useRest
we get back an object with 4 keys:
- execute: A function which wraps and, when called, executes the functions we have passed (
getName()
). - isPending: Wheter or not the async function is ongoing or not.
- data: The data we expect to get from the specified function (
name: string
). - error: Any error that might have occured.
const SomeComponent = () => {
const {execute, isPending, data, error} = useRest(getName);
useEffect(execute(), []);
if(isPending) {
return <div>Loading...</div>
}
if(error) {
return <div>An error occured: {error}</div>
}
if(data) {
return <div>My name is {data}</div>
}
return <div>Nothing to display.</div>
}
We want to execute the function when the component mounts, so we use useEffect
to do so.
Then we can render appropriate feedback for the request state.
This of course gets kind of annoying when you have to repeat this pattern for every request you make. This is where the react wrapper component comes into play.
Rest - react wrapper component
The Rest component is designed for the usage with useRest
, thus it expects the result of useRest
to be passed as props.
const SomeComponent = () => {
const {execute, isPending, data, error} = useRest(getName);
return (
<Rest
execute={execute}
isPending={isPending}
data={data}
error={error}
/>
)
}
You can of course simplify this by using the spread operator:
const SomeComponent = () => {
const nameRequest = useRest(getName);
return (
<Rest
{...nameRequest}
/>
)
}
No we are going to achieve the same result as before:
const SomeComponent = () => {
const nameRequest = useRest(getName);
return (
<Rest
{...nameRequest}
executeOnMount={(execute) => execute()}
renderOnPending={() => <div>Loading...</div>}
renderOnError={(error) => <div>An error occured: {error}</div>}
renderOnNoData={() => <div>Nothing to display.</div>}
render={(data) => <div>My name is {data}</div>}
/>
)
}