AutoSave.tsx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import React, { useEffect, useState } from 'react';
  2. import { Subscription, interval } from 'rxjs';
  3. import { take } from 'rxjs/operators';
  4. import { useTranslation } from 'react-i18next';
  5. import { useToasts } from 'react-toast-notifications';
  6. import useStore from '../store';
  7. import { saveFile } from '../apis';
  8. const index: React.FC = () => {
  9. const { t } = useTranslation('toast');
  10. const [{ info, annotations, initiated }] = useStore();
  11. const [isSaved, setSaved] = useState(false);
  12. const [isSaving, setSaving] = useState(false);
  13. const { addToast, removeAllToasts } = useToasts();
  14. let subscription: Subscription | null = null;
  15. useEffect(() => {
  16. if ((info.id && annotations.length) || (initiated && !annotations.length)) {
  17. if (subscription) subscription.unsubscribe();
  18. setSaved(false);
  19. setSaving(true);
  20. const observable = interval(1000);
  21. const data = {
  22. transaction_id: info.id,
  23. append_objects: annotations,
  24. };
  25. subscription = observable.pipe(take(4)).subscribe((x: number) => {
  26. if (x === 3) {
  27. saveFile(info.token, data).then(() => {
  28. setSaving(false);
  29. setSaved(true);
  30. });
  31. }
  32. });
  33. }
  34. return (): void => {
  35. if (subscription) subscription.unsubscribe();
  36. };
  37. }, [info, annotations]);
  38. useEffect(() => {
  39. removeAllToasts();
  40. if (isSaving) {
  41. addToast(t('saving'), {
  42. appearance: 'info',
  43. placement: 'bottom-center',
  44. });
  45. }
  46. if (!isSaving && isSaved) {
  47. addToast(t('saved'), {
  48. appearance: 'success',
  49. placement: 'bottom-center',
  50. autoDismiss: true,
  51. onDismiss: () => {
  52. removeAllToasts();
  53. },
  54. });
  55. }
  56. }, [isSaved, isSaving]);
  57. return <></>;
  58. };
  59. export default index;