Skip to content

Commit

Permalink
(#5) Adicionando hook useFetch
Browse files Browse the repository at this point in the history
Co-authored-by: Emily Sousa <diassousa@yahoo.com.br>
  • Loading branch information
sergiosacj and emysdias committed Sep 17, 2021
1 parent ecc3e01 commit a315202
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions frontend/src/helpers/useFetch.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import React from "react";
import { useState, useEffect, useCallback } from "react";

type Hook = (url: string, setMenuItem: (menuItem: string) => void) => boolean;

interface IuseFetch {
loading: boolean;
}

const useFetch: Hook = (url, setMenuItem) => {
const [loading, setLoading] = useState(true);

const getMenuItems = useCallback(async () => {
try {
const response = await fetch(url);
const data = await response.json();
setLoading(false);
setMenuItem(data);
} catch (error) {
setLoading(false);
throw new Error("useFetch: Can't access url");
}
}, [url, setMenuItem]);

useEffect(() => {
getMenuItems();
}, [getMenuItems]);

return loading;
};

export default useFetch;

0 comments on commit a315202

Please sign in to comment.