origin

React Hook is used, so this can be handled by custom hooks

design

Request interface, generally have such several parameters, such as data loading hasError, these several information to the page, open

import { useState, useEffect } from 'react';

export const request = <T>(url: string) :Promise<T> => {
  return new Promise((resolve, reject) = > {
    fetch(url)
      .then(
        (res) = > {
          if (res.ok) {
            return res.json();
          }
          return reject(res.body);
        },
        (err) = > reject(err)
      )
      .then((res: T) = > resolve(res));
  });
};

export const useInfo = <T>(url: string) = > {
  const [info, setInfo] = useState<T>();
  const [hasData, setHasData] = useState<boolean> (false);
  const [hasError, setHasError] = useState<boolean> (false);
  const [loading, setLoading] = useState<boolean> (false);
  useEffect(() = > {
    const getData = async () => {
      setLoading(true);
      try {
        const res = await request<T>(url);
        setHasData(true);
        setInfo(res);
      } catch (err) {
        setHasError(true);
      } finally {
        setLoading(false); }};if (url) {
      getData();
    }
  }, [url]);
  return [info, loading, hasData, hasError] as const;
};

Copy the code

Used in components

import * as React from 'react';
import { useInfo } from '. ';

interface DataInfo {
  count: number;
  data: string;
}
const Component = () = > {
  const [info, loading, hasData, hasError] = useInfo<DataInfo>('Requested URL');
  return <div>Your component</div>
}
export default Component
Copy the code

At the end

It’s a little bit simpler here, error handling doesn’t do anything, but that’s the general idea.