React Utilities
This library has a few react utilities.
useAsyncCall hook
This is a helper hook for making async calls.
Arguments
name | type | required | default | note |
---|---|---|---|---|
function | async Function | yes | the function will receive all the parameters from the execute call |
|
options | { onSuccess?: Function, onError?: Function, preventExecutionWhileLoading?: boolean; } | no | {} | a configuration object |
onSuccess | Function | no | undefined | a function to call after a successful call execution. Will receive the response as an argument. |
onError | Function | no | undefined | a function to call when the execution fail. Will receive the error as an argument. |
preventExecutionWhileLoading | boolean | no | true | whether to prevent the call execution if there's a previous call loading. This is useful in forms because it will prevent the form from being submitted again while the form is being submitted. |
It returns an object with the following properties:
-
execute
- the function you'll have to call. It receives any arguments you send to it and passes it to thefunction
you provided to the hook. -
isLoading
- whether the function is being executed right now. You can use it to display a loading indicator. -
isSuccess
- whether the function was called successfully. You can use it to display a message if the call was successful. -
isFailed
- whether the function call failed. You can use it to display an error message. -
error
- theError
thrown when calling the function -
response
- the response of the function call
Typescript Example
You can check the demo here.
import * as React from "react";
import { render } from "react-dom";
import { useAsyncCall } from "@livelix/react-utils";
interface User {
email: string;
}
function App() {
const call = useAsyncCall<User>(() => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ email: "example@example.com" });
}, 2000);
});
});
return (
<div>
{call.isSuccess ? (
<p>User email: {String(call.response?.email)}</p>
) : (
<button onClick={call.execute}>
{call.isLoading ? "Loading..." : "Get User"}
</button>
)}
</div>
);
}
render(<App />, document.getElementById("root"));
}
useStorageState hook
This hook is exactly as the useState
hook from react
, with the exception that this hook will store and get the value from the local storage.
Usage
import { useStorageState } from "@livelix/react-utils";
// First argument is the initial state
// Second argument is the storage key
// Third argument is the local storage - can be window.localStorage for web or AsyncStorage for react native
const [state, setState] = useStorageState('initialValue', 'storageKey', window.localStorage);