From 1e674d18c9fe39ddf0ecc6c493bc0f0ffc87db9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20T=C3=B6lle?= Date: Sat, 7 Nov 2020 19:14:41 +0100 Subject: [PATCH] fix(frontend): missing dependency in useCallback To avoid endless re-render we also have to use a constant empty array as the initialValue. --- frontend/src/components/ReportTopArtists.tsx | 11 ++++++++--- frontend/src/hooks/use-async.tsx | 4 ++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/frontend/src/components/ReportTopArtists.tsx b/frontend/src/components/ReportTopArtists.tsx index 581af3b..cbb8553 100644 --- a/frontend/src/components/ReportTopArtists.tsx +++ b/frontend/src/components/ReportTopArtists.tsx @@ -1,12 +1,14 @@ import React, { useMemo, useState } from "react"; import { Redirect } from "react-router-dom"; import { getTopArtists } from "../api/api"; +import { TimeOptions } from "../api/entities/time-options"; import { TimePreset } from "../api/entities/time-preset.enum"; -import { TopArtistsOptions } from "../api/entities/top-artists-options"; +import { TopArtistsItem } from "../api/entities/top-artists-item"; import { useAsync } from "../hooks/use-async"; import { useAuth } from "../hooks/use-auth"; import { ReportTimeOptions } from "./ReportTimeOptions"; -import { TimeOptions } from "../api/entities/time-options"; + +const INITIAL_REPORT_DATA: TopArtistsItem[] = []; export const ReportTopArtists: React.FC = () => { const { user } = useAuth(); @@ -21,7 +23,10 @@ export const ReportTopArtists: React.FC = () => { timeOptions, ]); - const { value: report, pending: isLoading } = useAsync(fetchData, []); + const { value: report, pending: isLoading } = useAsync( + fetchData, + INITIAL_REPORT_DATA + ); const reportHasItems = !isLoading && report.length !== 0; diff --git a/frontend/src/hooks/use-async.tsx b/frontend/src/hooks/use-async.tsx index 8811392..0220b23 100644 --- a/frontend/src/hooks/use-async.tsx +++ b/frontend/src/hooks/use-async.tsx @@ -1,4 +1,4 @@ -import React, { useState, useEffect, useCallback } from "react"; +import { useCallback, useEffect, useState } from "react"; type UseAsync = ( asyncFunction: () => Promise, @@ -25,7 +25,7 @@ export const useAsync: UseAsync = ( .then((response) => setValue(response)) .catch((err) => setError(err)) .finally(() => setPending(false)); - }, [asyncFunction]); + }, [asyncFunction, initialValue]); // Call execute if we want to fire it right away. // Otherwise execute can be called later, such as