Skip to content

Instantly share code, notes, and snippets.

@Falci
Last active March 3, 2020 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Falci/1fa3c9d27b10427cd9684ecbdcedbbe8 to your computer and use it in GitHub Desktop.
Save Falci/1fa3c9d27b10427cd9684ecbdcedbbe8 to your computer and use it in GitHub Desktop.
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');
@Falci
Copy link
Author

Falci commented Mar 3, 2020

const App = () => {
  const { data, loading, error } = useCurrentUser();

  if (loading) return (<div>Loading...</div>);
  if (error) return (<div>Error: {error}</div>);

  return <div>{data.name}</div>
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment