Skip to content

Instantly share code, notes, and snippets.

@3nvi
Created June 5, 2020 15:18
Show Gist options
  • Save 3nvi/3e33e9b908fb38d4be020084e230cce7 to your computer and use it in GitHub Desktop.
Save 3nvi/3e33e9b908fb38d4be020084e230cce7 to your computer and use it in GitHub Desktop.
import React from 'react';
import { useHistory } from 'react-router-dom';
const useQuery = ({ url }) => {
const history = useHistory();
const [apiData, setApiData] = React.useState();
React.useEffect(() => {
fetch(url)
.then(data => data.json())
.then(({ code, status, ...apiData }) => {
if (code > 400) {
history.replace(history.location.pathname, {
errorStatusCode: code
});
} else {
setApiData(apiData);
}
});
}, [url]);
return { data: apiData }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment