Browse Source

swr update

kaori 3 years ago
parent
commit
5ed04c7a22
1 changed files with 26 additions and 3 deletions
  1. 26 3
      packages/app/src/stores/global-notification.ts

+ 26 - 3
packages/app/src/stores/global-notification.ts

@@ -1,12 +1,19 @@
+import { SWRResponseWithUtils, withUtils } from '@growi/core';
 import { SWRResponse } from 'swr';
 import useSWRImmutable from 'swr/immutable';
 
-import { apiv3Get } from '../client/util/apiv3-client';
+
+import { apiv3Get, apiv3Put } from '../client/util/apiv3-client';
 // import { IBookmarkInfo } from '../interfaces/bookmark-info';
 
 
-export const useSWRxGlobalNotification = (globalNotificationId: string): SWRResponse<any, Error> => {
-  return useSWRImmutable(
+type Util = {
+  update(updateData: any): Promise<void>
+};
+
+
+export const useSWRxGlobalNotification = (globalNotificationId: string): SWRResponseWithUtils<Util, any, Error> => {
+  const swrResult = useSWRImmutable(
     globalNotificationId != null ? `/notification-setting/global-notification/${globalNotificationId}` : null,
     endpoint => apiv3Get(endpoint).then((response) => {
       return {
@@ -14,4 +21,20 @@ export const useSWRxGlobalNotification = (globalNotificationId: string): SWRResp
       };
     }),
   );
+
+
+  const update = async(updateData) => {
+    const { data, mutate } = swrResult;
+
+    if (data == null) {
+      return;
+    }
+
+    mutate({ ...data, ...updateData }, false);
+
+    // invoke API
+    await apiv3Put(`/notification-setting/global-notification/${globalNotificationId}`, updateData);
+  };
+
+  return withUtils<Util, any, Error>(swrResult, { update });
 };