Skip to content

Commit

Permalink
handle errors
Browse files Browse the repository at this point in the history
  • Loading branch information
nicokant committed Dec 21, 2023
1 parent 116b0db commit f3c484a
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/components/Layers.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ function Child({ node, ...other }) {


export default function Layers() {
const { data, isLoading } = useMetadata();
const { data, isLoading, error } = useMetadata();

if (isLoading) {
if (isLoading || error) {
return null;
}

Expand Down
11 changes: 10 additions & 1 deletion src/components/Map.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const geocoderApi = {
export default function Map() {
const mapContainer = useRef(null);
const { map, setMap } = useContext(MapContext);
const { data } = useMetadata();
const { data, error } = useMetadata();

useEffect(() => {
if (data && !map) {
Expand All @@ -71,6 +71,15 @@ export default function Map() {
}
}, [data, map]);

if (error) {
return (
<div>
<h2>An error occurred</h2>
<p>{error.info.message}</p>
</div>
)
}

return (
<div className="map-wrap">
<div ref={mapContainer} className="map" />
Expand Down
19 changes: 15 additions & 4 deletions src/hooks/useMetadata.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
import useSWR from "swr";

const fetcher = (url) => fetch(url, {
credentials: 'include'
}).then(res => res.json());

const fetcher = async url => {
const res = await fetch(url, { credentials: 'include' })

// If the status code is not in the range 200-299,
// we still try to parse and throw it.
if (!res.ok) {
const error = new Error('An error occurred while fetching the data.')
// Attach extra info to the error object.
error.info = await res.json()
error.status = res.status
throw error
}

return res.json()
}
export default function useMetadata() {
return useSWR(window.MAPS_API_URL.replace('{MAP_ID}', location.hash.slice(1)), fetcher);
}

0 comments on commit f3c484a

Please sign in to comment.