diff options
| author | jackyzha0 <[email protected]> | 2021-04-11 10:27:27 -0700 |
|---|---|---|
| committer | jackyzha0 <[email protected]> | 2021-04-11 10:27:27 -0700 |
| commit | 0144bfc9cc6c616a00a8171f3950a75ec948427e (patch) | |
| tree | 101d6c12471d411e9266cffa8e90176aff2e6fdb /frontend/src/http/useFetchPaste.js | |
| parent | base next bump (diff) | |
| download | ctrl-v-0144bfc9cc6c616a00a8171f3950a75ec948427e.tar.xz ctrl-v-0144bfc9cc6c616a00a8171f3950a75ec948427e.zip | |
base next refactor
Diffstat (limited to 'frontend/src/http/useFetchPaste.js')
| -rw-r--r-- | frontend/src/http/useFetchPaste.js | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/frontend/src/http/useFetchPaste.js b/frontend/src/http/useFetchPaste.js new file mode 100644 index 0000000..ba482f9 --- /dev/null +++ b/frontend/src/http/useFetchPaste.js @@ -0,0 +1,69 @@ +import {useEffect, useState} from 'react' +import {fetchPaste, fmtDateStr} from './shared' +import {LANGS} from "../components/renderers/Code"; + +const useFetchPaste = (id) => { + const [loading, setLoading] = useState(true) + const [err, setErr] = useState() + const [requiresAuth, setRequiresAuth] = useState(false) + const [validPass, setValidPass] = useState(false) + const [result, setResult] = useState({ + title: 'fetching paste...', + content: '', + language: LANGS.detect, + expiry: '', + }) + + const handleErr = error => { + const resp = error.response + + // network err + if (!resp) { + setErr(error.toString()) + return + } + + // password protected + if (resp.status === 401) { + setRequiresAuth(true) + return + } + + // catch all + const errTxt = `${resp.status}: ${resp.data}` + setErr(errTxt) + } + + // callback to try verifying with password + const getWithPassword = (password, errorCallback) => { + fetchPaste(id, password) + .then(resp => { + setValidPass(true) + setStateFromData(resp.data) + }) + .catch(e => errorCallback(e.response.data)) + } + + + const setStateFromData = (data) => { + document.title = data.title + setResult({ + title: data.title, + content: data.content, + language: data.language, + expiry: fmtDateStr(data.expiry) + }) + } + + // initial fetch + useEffect(() => { + fetchPaste(id) + .then(resp => setStateFromData(resp.data)) + .catch(handleErr) + .finally(() => setLoading(false)) + }, [id]) + + return { loading, err, requiresAuth, validPass, getWithPassword, result } +} + +export default useFetchPaste
\ No newline at end of file |