Skip to content

10 Fetch Status

JP Barbosa edited this page Oct 15, 2022 · 5 revisions

Fetch Status

Components

Components

Add loading and error to useFetch hook

code ./src/hooks/useFetch.ts
import ..., { AxiosError } from 'axios';
...

export const useFetch = <...>(...) => {
  ...
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<AxiosError>();

  ...

  useEffect(() => {
    const callFetchFunction = async () => {
      setLoading(true);
      try {
        const res = await axios.get<T[]>(url, { params: options });
        setRecords(res.data);
      } catch (e) {
        setError(e as AxiosError);
      }
      setLoading(false);
    };
    callFetchFunction();
  }, [url, options, version]);

  return { ..., loading, error };
};

Add loading and error to RecordIndex

code ./src/pages/Record/index.tsx
...

export const RecordIndex = <...>(...) => {
  ...
  const { ..., loading, error } = useFetch<T>(...);

  ...

  return (
    <div className="page">
      <div className="content">
        <RecordList<T>
          ...
          loading={loading}
          error={error}
        />
        ...
      </div>
    </div>
  );
};

Add loading and error to RecordListProps

code ./src/interfaces/PagesProps.ts
import { AxiosError } from 'axios';

...

export interface RecordListProps<T> {
  ...
  loading: boolean;
  error?: AxiosError;
}

Add loading and error to RecordList

code ./src/pages/Record/List.tsx
...
import { Status } from '../../components/Status';
import { RecordError } from '../../components/RecordError';

export const RecordList = <...>({
  ...
  loading,
  error,
}: RecordListProps<T>) => {

  return (
    <div className="list">
      {error && <RecordError error={error} />}
      <div>
        ...
      </div>
      {loading && <Status text="Loading..." />}
    </div>
  );
};

Create Status

code ./src/components/Status.tsx
interface IProps {
  text: string;
}

export const Status: React.FC<IProps> = ({ text }) => {
  return (
    <div className="status">
      <span className="status-text">{text}</span>
    </div>
  );
};

Create RecordError

code ./src/components/RecordError.tsx
import { AxiosError } from 'axios';

interface IProps {
  error: AxiosError<any>;
}

export const RecordError: React.FC<IProps> = ({ error }) => {
  return (
    <div className="error">
      <div>
        <b>Message:</b> {error.message}
      </div>
      <div>
        <b>URL:</b> {error.config?.url}
      </div>
      {error.response?.data.message && (
        <div>
          <b>Details:</b> {error.response?.data.message}
        </div>
      )}
    </div>
  );
};

Result

Result

Commit

git add .
git commit -m "Fetch Status"

Next step: Mutation Status