Last active
March 3, 2020 21:31
-
-
Save Falci/1fa3c9d27b10427cd9684ecbdcedbbe8 to your computer and use it in GitHub Desktop.
This file contains 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
import { useState, useEffect } from 'react'; | |
const STORAGE_KEY = 'auth_token'; | |
const getToken = () => window.localStorage.getItem(STORAGE_KEY); | |
const clearToken = () => window.localStorage.removeItem(STORAGE_KEY); | |
const setToken = token => | |
token ? window.localStorage.setItem(STORAGE_KEY, token) : clearToken(); | |
const useApi = (url, options = {}) => { | |
const [data, setData] = useState(null); | |
const [loading, setLoading] = useState(true); | |
const [error, setError] = useState(null); | |
const headers = { | |
...options.headers, | |
Authorization: getToken(), | |
Accept: 'application/json' | |
}; | |
const fetchData = () => { | |
fetch(url, { ...options, headers }) | |
.then(async resp => { | |
setToken(resp.headers.get('authorization')); | |
if (resp.ok) { | |
setData(await resp.json()); | |
} else { | |
setError(resp.statusText); | |
} | |
}) | |
.catch(e => setError(e)) | |
.finally(() => setLoading(false)); | |
}; | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
useEffect(() => fetchData(), []); | |
return { data, loading, error }; | |
}; | |
export default useApi; | |
export const useCurrentUser = () => useApi('/api/users/me'); |
Author
Falci
commented
Mar 3, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment