Skip to content

Instantly share code, notes, and snippets.

@jbouder
Last active July 9, 2023 13:08
Show Gist options
  • Save jbouder/5f3189cf8b5da2d3de65d971eb33ac93 to your computer and use it in GitHub Desktop.
Save jbouder/5f3189cf8b5da2d3de65d971eb33ac93 to your computer and use it in GitHub Desktop.
// some-component.tsx
import React, { useEffect, useState } from 'react'(
import useDocumentApi from '../../hooks/useDocumentApi';
import useAuth from '../../hooks/useAuth';
export const SomeComponent = (): React.ReactElement => {
const { getDocuments, loading, documents } = useDocumentApi();
const { isSignedIn } = useAuth();
const [data, setData] = useState<TableData[]>();
useEffect(() => {
if (isSignedIn) {
getDocuments();
}
}, [isSignedIn]);
useEffect(() => {
if (documents) {
// Do something
}
}, [documents]);
return (...);
}
// useDocumentApi.ts
import { useState } from 'react';
import { Document } from '../types/documents';
import axios from '../axios';
const useDocumentApi = () => {
const [loading, setLoading] = useState<boolean>(false);
const [documents, setDocuments] = useState<Document[]>();
const [document, setDocument] = useState<Document>();
const [error, setError] = useState<string | null>(null);
const getDocuments = (): void => {
setLoading(true);
axios
.get('/documents')
.then((response) => {
return response.data;
})
.then((data) => {
setDocuments(data);
})
.catch((error) => {
setError(error.message);
})
.finally(() => {
setLoading(false);
});
}
};
return {
loading,
documents,
document,
error,
getDocuments,
getDocument,
};
};
export default useDocumentApi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment