Skip to content

Instantly share code, notes, and snippets.

@deguchi
Last active September 24, 2021 02:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deguchi/cfee7bbc6bdfef6a3105b92782492589 to your computer and use it in GitHub Desktop.
Save deguchi/cfee7bbc6bdfef6a3105b92782492589 to your computer and use it in GitHub Desktop.
import React, { useState} from 'react'
import useSWR from 'swr'
import { fetcher } from './fetcher'
const ENDPOINT = 'https://unitrad.calil.jp/v1/'
const REGION = 'recipe'
export const useSwr = (q: string) => {
const [url, setUrl] = useState(`${ENDPOINT}/search?region=${REGION}&free=${encodeURIComponent(q)}`)
const [interval, setPollingInterval] = useState(100)
const {data, error} = useSWR(url, fetcher, {
refreshInterval: interval,
onSuccess: (data) => {
if (data.running === true) {
setUrl(`${ENDPOINT}/polling?region=${REGION}&uuid=${data.uuid}`)
setPollingInterval(500)
} else {
setPollingInterval(0)
}
}
})
return {
data,
isLoading: !error && !data,
isError: error
}
}
export default useSwr;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment