Home > AI > Frontend > ReactJS >

Data fetching with useSWR

The issue of data fetching in ReactJS has been addressed using useSWR. In comparison to alternative packages such as ReactQuery, SWR offers a simpler solution. Our needs are fairly basic, including bearer token support, caching, managing loading states, and supporting TypeScript.

One scenario is when displaying /admin/practice/asq, where the question count retrieved in /admin/practice is showcased. Additionally, upon refreshing the page in /admin/practice, we aim to avoid re-requesting APIs slow performance, bad user experience accordingly.

Given that we will be loading multiple APIs, the essential code snippets are provided below.

export const fetcher = async (urls: string[], token: string) => {
  const requests = urls.map(url =>
    fetch(url, { headers: { Authorization: `Bearer ${token}` }})
  );

  const responses = await Promise.all(requests);

  const responseData = await Promise.all(
    responses.map(async response => {
      if (!response.ok) {
        throw new Error('Failed to fetch data');
      }
      return response.json();
    })
  );

  return responseData;
};

const PracticeListPage: React.FC = () => {
  const {token, error: tokenError }: IAuthContext = useContext(AuthContext)

  const { data, error: dataError, isLoading } = useSWR([
    API_V1[`count_ra`], API_V1[`count_di`],
API_V1[`count_rs`], API_V1[`count_rl`], API_V1[`count_asq`],
    API_V1[`count_swt`], API_V1[`count_we`],
    API_V1[`count_rfib`], API_V1[`count_rmcm`], API_V1[`count_rmcs`], API_V1[`count_ro`], API_V1[`count_rwfib`],
    API_V1[`count_sst`], API_V1[`count_mcm`], API_V1[`count_fib`], API_V1[`count_hcs`], API_V1[`count_hiw`], API_V1[`count_mcs`], API_V1[`count_smw`], API_V1[`count_wfd`],

    API_V1[`questionInfos_ra`], API_V1[`questionInfos_di`], API_V1[`questionInfos_rs`], API_V1[`questionInfos_rl`], API_V1[`questionInfos_asq`],
    API_V1[`questionInfos_swt`], API_V1[`questionInfos_we`],
    API_V1[`questionInfos_rfib`], API_V1[`questionInfos_rmcm`], API_V1[`questionInfos_rmcs`], API_V1[`questionInfos_ro`], API_V1[`questionInfos_rwfib`],
    API_V1[`questionInfos_sst`], API_V1[`questionInfos_mcm`], API_V1[`questionInfos_fib`], API_V1[`questionInfos_hcs`], API_V1[`questionInfos_hiw`], API_V1[`questionInfos_mcs`], API_V1[`questionInfos_smw`], API_V1[`questionInfos_wfd`],
], (url) => fetcher(url, token));
}

Leave a Reply