Async link
Examples
Check out the Usage section for details about how and when to use the AsyncLink
component.
Basic AsyncLink
This example shows the basic usage of the AsyncLink component. When you click on the link, the onTrigger
prop callback can return either true
, false
, or a promise. In this example, it shows the assigned message, "Wait...", and after two seconds this message disappears and shows the text "Submitted".
import React, { useState, useEffect } from 'react';
import { AsyncLink } from '@jutro/router/';
export const BasicAsyncLink = () => {
const [showMessage, setShowMessage] = useState(false);
const [message, setMessage] = useState('Submit');
const asyncMessage = "Wait...";
useEffect(() => {
let timerId;
if (showMessage) {
timerId = setTimeout(() => {
setShowMessage(false);
setMessage('Submited');
}, 2000);
}
return () => clearTimeout(timerId); // Clear the timeout when the component unmounts or showMessage changes
}, [showMessage]);
function clickFunction() {
setShowMessage(true);
setMessage(asyncMessage);
}
return (
<div>
<AsyncLink
message={asyncMessage}
onTrigger={clickFunction}
to="/test"
>
{message}
</AsyncLink>
</div>
);
};
AsyncLink Messages
You can use the props toMessage
and failToMessage
to show messages depending on whether the returned promise is successful or rejected.
Additionally, you can use the prop failTo
to redirect to a different path in case the promise fails.
import React, { useState } from 'react';
import { AsyncLink } from '@jutro/router/';
export const MessagesAsyncLink = () => {
const [successLinkText, setSuccessLinkText] = useState('Success link');
const [failureLinkText, setFailureLinkText] = useState('Failure link');
const asyncMessage = "Wait...";
const successMessage = "Action completed successfully!";
const failureMessage = "Action failed. Please try again.";
const timer = 2000;
const handleSuccess = () => {
setSuccessLinkText(asyncMessage);
setTimeout(() => {
setSuccessLinkText(successMessage);
setTimeout(() => setSuccessLinkText('Success link'), timer);
}, 2000);
};
const handleFailure = () => {
setFailureLinkText(asyncMessage);
setTimeout(() => {
setFailureLinkText(failureMessage);
setTimeout(() => setFailureLinkText('Failure link'), timer);
}, 2000);
};
return (
<div>
<div>
<AsyncLink
message={asyncMessage}
toMessage={successMessage}
failToMessage={failureMessage}
onTrigger={handleSuccess}
to="/async-link#asynclink-messages"
>
{successLinkText}
</AsyncLink>
</div>
<div>
<AsyncLink
message={asyncMessage}
toMessage={successMessage}
failToMessage={failureMessage}
onTrigger={handleFailure}
to="/async-link#asynclink-messages"
>
{failureLinkText}
</AsyncLink>
</div>
</div>
);
};
Was this page helpful?