useSWR instead of custom useAxiosGet hook for cache reuse

This commit is contained in:
spencerwooo 2022-01-24 20:50:43 +08:00
parent 17263feea9
commit b47dd88d1a
No known key found for this signature in database
GPG key ID: 24CD550268849CA0
7 changed files with 18 additions and 26 deletions

View file

@ -1,19 +1,20 @@
import axios from 'axios'
import useSWR, { SWRResponse } from 'swr'
import { Dispatch, Fragment, SetStateAction, useState } from 'react'
import AwesomeDebouncePromise from 'awesome-debounce-promise'
import { useAsync } from 'react-async-hook'
import useConstant from 'use-constant'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { Dispatch, Fragment, SetStateAction, useState } from 'react'
import { Dialog, Transition } from '@headlessui/react'
import Link from 'next/link'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { Dialog, Transition } from '@headlessui/react'
import { OdDriveItem, OdSearchResult } from '../types'
import { LoadingIcon } from './Loading'
import { getFileIcon } from '../utils/getFileIcon'
import useAxiosGet from '../utils/fetchOnMount'
import siteConfig from '../config/site.json'
import { fetcher } from '../utils/fetchWithSWR'
/**
* Extract the searched item's path in field 'parentReference' and convert it to the
@ -101,27 +102,18 @@ function SearchResultItemTemplate({
}
function SearchResultItemLoadRemote({ result }: { result: OdSearchResult[number] }) {
const {
content,
error,
validating,
}: {
content: OdDriveItem
error: string
validating: boolean
} = useAxiosGet(`/api/item?id=${result.id}`)
const { data, error }: SWRResponse<OdDriveItem, string> = useSWR(`/api/item?id=${result.id}`, fetcher)
if (error) {
return <SearchResultItemTemplate driveItem={result} driveItemPath={''} itemDescription={error} disabled={true} />
}
if (validating) {
if (!data) {
return (
<SearchResultItemTemplate driveItem={result} driveItemPath={''} itemDescription={'Loading ...'} disabled={true} />
)
}
const driveItemPath = `${mapAbsolutePath(content.parentReference.path)}/${encodeURIComponent(content.name)}`
const driveItemPath = `${mapAbsolutePath(data.parentReference.path)}/${encodeURIComponent(data.name)}`
return (
<SearchResultItemTemplate
driveItem={result}

View file

@ -9,7 +9,7 @@ import DownloadButtonGroup from '../DownloadBtnGtoup'
import { DownloadBtnContainer, PreviewContainer } from './Containers'
const CodePreview: FC<{ file: any }> = ({ file }) => {
const { content, error, validating } = useAxiosGet(file['@microsoft.graph.downloadUrl'])
const { response: content, error, validating } = useAxiosGet(file['@microsoft.graph.downloadUrl'])
useEffect(() => {
if (typeof window !== 'undefined') {

View file

@ -19,7 +19,7 @@ const MarkdownPreview: FC<{ file: any; path: string; standalone?: boolean }> = (
path,
standalone = true,
}) => {
const { content, error, validating } = useAxiosGet(file['@microsoft.graph.downloadUrl'])
const { response: content, error, validating } = useAxiosGet(file['@microsoft.graph.downloadUrl'])
// The parent folder of the markdown file, which is also the relative image folder
const parentPath = path.substring(0, path.lastIndexOf('/'))

View file

@ -5,7 +5,7 @@ import useAxiosGet from '../../utils/fetchOnMount'
import { DownloadBtnContainer, PreviewContainer } from './Containers'
const TextPreview = ({ file }) => {
const { content, error, validating } = useAxiosGet(file['@microsoft.graph.downloadUrl'])
const { response: content, error, validating } = useAxiosGet(file['@microsoft.graph.downloadUrl'])
if (error) {
return (
<PreviewContainer>

View file

@ -12,7 +12,7 @@ const parseDotUrl = (content: string): string | undefined => {
}
const TextPreview = ({ file }) => {
const { content, error, validating } = useAxiosGet(file['@microsoft.graph.downloadUrl'])
const { response: content, error, validating } = useAxiosGet(file['@microsoft.graph.downloadUrl'])
if (error) {
return (
<PreviewContainer>

View file

@ -1,7 +1,7 @@
import axios from 'axios'
import type { NextApiRequest, NextApiResponse } from 'next'
import { encodePath, getAccessToken } from '.'
import { getAccessToken } from '.'
import apiConfig from '../../config/api.json'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {

View file

@ -1,20 +1,20 @@
import axios from 'axios'
import { useEffect, useState } from 'react'
// Custom hook to fetch raw file content on mount
export default function useAxiosGet(fetchUrl: string): { content: any; error: string; validating: boolean } {
const [content, setContent] = useState('')
// Custom hook to axios get a URL or API endpoint on mount
export default function useAxiosGet(fetchUrl: string): { response: any; error: string; validating: boolean } {
const [response, setResponse] = useState('')
const [validating, setValidating] = useState(true)
const [error, setError] = useState('')
useEffect(() => {
axios
.get(fetchUrl)
.then(res => setContent(res.data))
.then(res => setResponse(res.data))
.catch(e => setError(e.message))
.finally(() => {
setValidating(false)
})
}, [fetchUrl])
return { content, error, validating }
return { response, error, validating }
}