Created
July 9, 2023 13:06
-
-
Save jbouder/113e55ca55032da5988ecf79e5027ddc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 { loading, documents } = useDocumentApi(); | |
const { isSignedIn } = useAuth(); | |
const [data, setData] = useState<TableData[]>(); | |
useEffect(() => { | |
if (isSignedIn && documents) { | |
// Do something | |
} | |
}, [isSignedIn, documents]); | |
return (...); | |
} | |
// useDocumentApi.ts | |
import { useEffect, 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); | |
useEffect(() => { | |
getDocuments(); | |
}, []); | |
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