daily pastebin goal
24%
SHARE
TWEET

Untitled

a guest Jan 20th, 2019 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Collection, IModelConstructor, View } from 'datx';
  2. import { IJsonapiModel, IJsonapiView, IRequestOptions, jsonapi } from 'datx-jsonapi';
  3. import { useEffect, useMemo, useState } from 'react';
  4.  
  5. const JsonapiView = jsonapi(View);
  6.  
  7. export const useFetchAll = <T extends IJsonapiModel>(
  8.   collection: Collection,
  9.   model: IModelConstructor<T>,
  10.   options?: IRequestOptions,
  11. ): {
  12.   view?: View<T> & IJsonapiView;
  13.   error?: any;
  14.   isLoading: boolean;
  15.   startedAt?: Date;
  16.   finishedAt?: Date;
  17. } => {
  18.   const [state, setState] = useState<{
  19.     error?: any;
  20.     view?: View<T> & IJsonapiView;
  21.     startedAt?: Date;
  22.     finishedAt?: Date;
  23.   }>({});
  24.  
  25.   if (!state.view) {
  26.     const view = new JsonapiView(model, collection) as View<T> & IJsonapiView;
  27.     setState((oldState) => ({ ...oldState, view }));
  28.   }
  29.  
  30.   const load = () => {
  31.     if (state.view && !state.startedAt) {
  32.       setState((oldState) => ({ ...oldState, startedAt: new Date() }));
  33.       state.view.fetchAll(options).then((response) => {
  34.         setState((oldState) => ({
  35.           ...oldState,
  36.           error: response.error,
  37.           finishedAt: new Date(),
  38.         }));
  39.       });
  40.     }
  41.   };
  42.  
  43.   useEffect(load, []);
  44.  
  45.   return useMemo(() => ({
  46.     ...state,
  47.     isLoading: Boolean(state.startedAt) && !Boolean(state.finishedAt),
  48.   }), [state]);
  49. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top