Explorar el Código

81110 use SWR to fetch data

Yohei-Shiina hace 4 años
padre
commit
bb8b960ac7

+ 5 - 11
packages/app/src/components/Navbar/SubNavButtons.tsx

@@ -10,7 +10,7 @@ import PageManagement from '../Page/PageManagement';
 import { useSWRPageInfo } from '../../stores/page';
 import { toastError } from '../../client/util/apiNotification';
 import { apiv3Put } from '../../client/util/apiv3-client';
-
+import { useSWRxLikerList } from '../../stores/user';
 
 type SubNavButtonsProps= {
   appContainer: AppContainer,
@@ -25,7 +25,8 @@ const SubNavButtons: FC<SubNavButtonsProps> = (props: SubNavButtonsProps) => {
   const { editorMode } = navigationContainer.state;
   const isViewMode = editorMode === 'view';
   const { data: pageInfo, error: pageInfoError, mutate: mutatePageInfo } = useSWRPageInfo(pageId);
-  const [likers, setLikers] = useState([]);
+  const { data: likers, mutate: mutateLikerList } = useSWRxLikerList(pageInfo?.likerIds);
+
   const likeClickhandler = useCallback(async() => {
     const { isGuestUser } = appContainer;
 
@@ -43,15 +44,8 @@ const SubNavButtons: FC<SubNavButtonsProps> = (props: SubNavButtonsProps) => {
     }
   }, [pageInfo]);
 
-  const updateLikers = async() => {
-    if (pageInfo != null && pageInfo.likerIds.length > 0) {
-      const res: any = await props.appContainer.apiGet('/users.list', { user_ids: [...pageInfo.likerIds].join(',') });
-      setLikers(res.users);
-    }
-  };
-
   useEffect(() => {
-    updateLikers();
+    mutateLikerList();
   }, [pageInfo]);
 
   if (pageInfoError != null || pageInfo == null) {
@@ -66,7 +60,7 @@ const SubNavButtons: FC<SubNavButtonsProps> = (props: SubNavButtonsProps) => {
           pageId={pageId}
           sumOfLikers={sumOfLikers}
           isLiked={isLiked}
-          likers={likers}
+          likers={likers || []}
           onLikeClicked={likeClickhandler}
         >
         </PageReactionButtons>

+ 12 - 0
packages/app/src/stores/user.tsx

@@ -0,0 +1,12 @@
+import useSWR, { SWRResponse } from 'swr';
+import { IUser } from '../interfaces/user';
+import { apiGet } from '../client/util/apiv1-client';
+
+const userFetcher = (endpoint:string, ids:string) => {
+  return apiGet(endpoint, { user_ids: ids }).then((response:any) => response.users);
+};
+
+export const useSWRxLikerList = (likerIds?: string[]): SWRResponse<IUser[], Error> => {
+  const shouldFetch = likerIds != null && likerIds.length > 0;
+  return useSWR<any>(shouldFetch ? ['/users.list', [...likerIds].join(',')] : null, userFetcher);
+};