Last active
July 9, 2023 13:08
-
-
Save jbouder/5f3189cf8b5da2d3de65d971eb33ac93 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 { 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