Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: move fetch-logic to custom hook to separate responsibilities #187

Merged
merged 5 commits into from
Feb 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 37 additions & 24 deletions web/src/common/components/VersionText.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,55 @@
import { Typography } from '@equinor/eds-core-react'
import axios, { AxiosError, AxiosResponse } from 'axios'
import { useEffect, useState } from 'react'
import axios, { AxiosResponse } from 'axios'

export const VersionText = (): JSX.Element => {
const [commitInfo, setCommitInfo] = useState<{ [key: string]: string }>({
type CommitInfo = {
hash: string
date: string
refs: string
}

const useCommitInfo = () => {
const [commitInfo, setCommitInfo] = useState<CommitInfo>({
hash: '',
date: '',
refs: '',
})

useEffect(() => {
axios
.get('version.txt')
.then((response: AxiosResponse<string>) => {
const versionFile: { [key: string]: string } = Object.fromEntries(
response.data.split('\n').map((line) => {
return line.split(': ')
})
const fetchVersionFile = () =>
axios
.get('version.txt')
.then((res: AxiosResponse<string>) =>
Object.fromEntries(
res.data.split('\n').map((line) => line.split(': '))
)
)
setCommitInfo(versionFile)
})
.catch(() => null)
.catch((error: AxiosError) => {
throw new Error(
`Could not read version file, ${error.response?.data ?? error}`
)
})
fetchVersionFile().then((commitInfo) => setCommitInfo(commitInfo))
}, [])

return commitInfo
}

export const VersionText = () => {
const commitInfo = useCommitInfo()

return (
<p>
Version:{' '}
{commitInfo.hash !== '' && commitInfo.date !== '' && (
<>
<Typography
link
href={`https://github.com/equinor/template-fastapi-react/commit/${commitInfo.hash}`}
>
{commitInfo.refs === '' ? commitInfo.hash : commitInfo.refs}
</Typography>{' '}
({commitInfo.date})
</>
)}
<>
<Typography
link
href={`https://github.com/equinor/template-fastapi-react/commit/${commitInfo.hash}`}
>
{commitInfo.refs === '' ? commitInfo.hash : commitInfo.refs}
</Typography>{' '}
{commitInfo.date}
</>
</p>
)
}