Skip to content

Commit

Permalink
Implement device action using SWR
Browse files Browse the repository at this point in the history
  • Loading branch information
user890104 committed Sep 20, 2024
1 parent bbf6205 commit 48a5755
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 11 deletions.
24 changes: 24 additions & 0 deletions src/hooks/useDeviceAction.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { authenticatedFetcher } from '../utils/swr.js';

export default function useDeviceAction(deviceId, action) {
const url = import.meta.env.PORTIER_URL.concat('api/device/').concat(deviceId).concat('/').concat(action);
let error = null;

async function execute() {
try {
return await authenticatedFetcher(url, {
method: 'POST',
});
}
catch (e) {
error = {
status: e.status,
};
}
}

return {
execute,
error,
};
}
17 changes: 6 additions & 11 deletions src/widgets/DeviceActionButton/DeviceActionButton.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Button } from 'react-bootstrap';
import { useTranslation } from 'react-i18next';
import PropTypes from 'prop-types';

import { useDeviceActionMutation } from '../../features/apiSlice.js';
import useDeviceAction from '../../hooks/useDeviceAction.js';
import RedirectToLogin from '../RedirectToLogin.jsx';
import { sleep } from '../../utils/time.js';

Expand Down Expand Up @@ -42,10 +42,10 @@ const DeviceActionButton = ({
}) => {
const [ disabled, setDisabled ] = useState(false);

const [ execute, {
isError,
const {
execute,
error,
} ] = useDeviceActionMutation();
} = useDeviceAction(deviceId, action);

const {t} = useTranslation();
const type = types?.[action] || {
Expand All @@ -55,12 +55,7 @@ const DeviceActionButton = ({

async function handleClick() {
setDisabled(true);

await execute({
deviceId,
action,
});

await execute();
await sleep(3000);
setDisabled(false);
}
Expand All @@ -74,7 +69,7 @@ const DeviceActionButton = ({
<i className={icon} />
<div>{label}</div>
</Button>
{isError && [401, 403].includes(error.status) && <RedirectToLogin />}
{error?.status && [401, 403].includes(error.status) && <RedirectToLogin />}
</>);
};

Expand Down

0 comments on commit 48a5755

Please sign in to comment.