Skip to content

09 Fetch Callback

JP Barbosa edited this page Apr 28, 2021 · 5 revisions

Fetch Callback

Components

Components

Add setVersion to useFetch

code ./src/hooks/useFetch.ts
...

export const useFetch = <...>(...) => {
  ...
  const [version, setVersion] = useState(+new Date());

  ...

  useEffect(() => {
    ...
  }, [..., version]);
  return { ..., setVersion };
};

Add callback to mutationsHook

code ./src/hooks/useMutation.ts
...

export const useMutation = <T extends Record>(
  ...,
  callback?: Function
) => {
  ...

  const wrap = (fn: Action<T>) => {
    return async (record: T) => {
      fn(record).then(() => {
        if (callback) {
          callback();
        }
      });
    };
  };

  const create: Action<T> = wrap(async (record: T) => {
    await axios.post(url, record);
  });

  const update: Action<T> = wrap(async (record: T) => {
    await axios.put(`${url}/${record.id}`, record);
  });

  const remove: Action<T> = wrap(async (record: T) => {
    await axios.delete(`${url}/${record.id}`);
  });

  return {
    ...
  };
};

Add setVersion to RecordIndex

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

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

  const callback = () => {
    setVersion(+new Date());
    setActiveRecord(emptyRecord);
  };

  return (
    <div className="page">
      <div className="content">
        ...
        <RecordMutations<T>
          ...
          callback={callback}
        />
      </div>
    </div>
  );
};

Add callback to RecordMutationsProps

code ./src/interfaces/PagesProps.ts
export interface RecordMutationsProps<T> {
  ...
  callback: Function;
}

Add callback to RecordMutations

code ./src/pages/Record/Mutations.tsx
...

export const RecordMutations = <T extends Record>({
  ...
  callback,
}: RecordMutationsProps<T>) => {
  const { ... } = useMutation<T>(..., callback);

  return (
    ...
  );
};

Result

Result

Commit

git add .
git commit -m "Fetch Callback"

Next step: Fetch Status